### Retry Logic with Exponential Backoff and Capped Delay in TypeScript Source: https://github.com/gcanti/retry-ts/blob/master/README.md Demonstrates how to use retry-ts to implement a retry policy for a failing API call. It defines a policy combining exponential backoff with a maximum delay and a limit on the number of retries. The example logs the delay between retries and shows the final result after exhausting retries. ```typescript import { log } from 'fp-ts/Console' import * as E from 'fp-ts/Either' import { pipe } from 'fp-ts/function' import * as O from 'fp-ts/Option' import * as TE from 'fp-ts/TaskEither' import { capDelay, exponentialBackoff, limitRetries, Monoid, RetryStatus } from 'retry-ts' import { retrying } from 'retry-ts/Task' const policy = capDelay(2000, Monoid.concat(exponentialBackoff(200), limitRetries(5))) const fakeAPI = TE.left('API errored out') const logDelay = (status: RetryStatus) => TE.rightIO( log( pipe( status.previousDelay, O.map((delay) => `retrying in ${delay} milliseconds...`), O.getOrElse(() => 'first attempt...') ) ) ) const result = retrying(policy, (status) => pipe(logDelay(status), TE.apSecond(fakeAPI)), E.isLeft) result().then((e) => console.log(e)) ``` -------------------------------- ### Apply Retry Policy and Delay Execution in TypeScript Source: https://context7.com/gcanti/retry-ts/llms.txt Demonstrates the 'applyAndDelay' function from 'retry-ts/Task', which applies a given retry policy to a starting retry status and returns a Task that resolves after the calculated delay. This is useful for implementing waiting periods between retries. It requires importing 'Task' from 'fp-ts' and 'exponentialBackoff', 'defaultRetryStatus' from 'retry-ts'. ```typescript import * as T from 'fp-ts/Task' import { exponentialBackoff, defaultRetryStatus } from 'retry-ts' import { applyAndDelay } from 'retry-ts/Task' const policy = exponentialBackoff(100) // Apply policy and wait for the delay const delayedStatus = applyAndDelay(policy, defaultRetryStatus) delayedStatus().then((status) => { console.log(`Waited ${status.previousDelay} milliseconds`) console.log(`Cumulative delay: ${status.cumulativeDelay}ms`) console.log(`Iteration: ${status.iterNumber}`) }) // Output after 100ms: // Waited some(100) milliseconds // Cumulative delay: 100ms // Iteration: 1 ``` -------------------------------- ### Retry ReaderTask Actions with Environment in TypeScript Source: https://context7.com/gcanti/retry-ts/llms.txt Illustrates retrying a ReaderTaskEither-based action that depends on an environment configuration. The 'retrying' function from 'retry-ts/ReaderTask' is used here. The example defines an 'Config' interface for the environment, simulates an API call that depends on this config and may fail, and applies a retry policy. It requires 'fp-ts' (Either, ReaderTaskEither) and 'retry-ts' (constantDelay, limitRetries, Monoid). ```typescript import * as E from 'fp-ts/Either' import { pipe } from 'fp-ts/function' import * as RTE from 'fp-ts/ReaderTaskEither' import { constantDelay, limitRetries, Monoid, RetryStatus } from 'retry-ts' import { retrying } from 'retry-ts/ReaderTask' // Environment configuration interface Config { apiUrl: string maxRetries: number } let callCount = 0 // API call that depends on config and may fail const apiCall = (status: RetryStatus) => RTE.fromTaskEither(async () => { callCount++ console.log(`Attempt ${callCount}`) if (callCount < 3) { return E.left('Connection failed') } return E.right('Data received') }) const policy = Monoid.concat(constantDelay(50), limitRetries(5)) const program = retrying(policy, apiCall, E.isLeft) // Run with configuration const config: Config = { apiUrl: 'https://api.example.com', maxRetries: 5 } program(config)().then((result) => { console.log(result) // right("Data received") }) // Output: // Attempt 1 // Attempt 2 // Attempt 3 // right("Data received") ``` -------------------------------- ### Exponential Backoff Retry Policy in TypeScript Source: https://context7.com/gcanti/retry-ts/llms.txt Creates a retry policy that doubles the delay with each iteration, starting from a specified initial delay. This policy is useful for implementing strategies where longer waits are acceptable after multiple failures. It requires the 'retry-ts' library and uses 'applyPolicy' to simulate retry attempts. ```typescript import { exponentialBackoff, applyPolicy, defaultRetryStatus } from 'retry-ts' // Create an exponential backoff policy starting at 100ms const policy = exponentialBackoff(100) // Apply policy multiple times to see delay progression const status1 = applyPolicy(policy, defaultRetryStatus) console.log(status1.previousDelay) // some(100) - first retry: 100ms const status2 = applyPolicy(policy, status1) console.log(status2.previousDelay) // some(200) - second retry: 200ms const status3 = applyPolicy(policy, status2) console.log(status3.previousDelay) // some(400) - third retry: 400ms const status4 = applyPolicy(policy, status3) console.log(status4.previousDelay) // some(800) - fourth retry: 800ms ``` -------------------------------- ### Retry Task Actions with retrying in TypeScript Source: https://context7.com/gcanti/retry-ts/llms.txt Shows how to retry a TaskEither-based action using the 'retrying' function from 'retry-ts/Task'. This example simulates a failing API call and logs retry attempts with their delays. The function takes a retry policy, a function that receives retry status and returns a TaskEither, and a predicate to determine if retries should continue. It depends on 'fp-ts' for TaskEither and Option, and 'retry-ts' for policies. ```typescript import { log } from 'fp-ts/Console' import * as E from 'fp-ts/Either' import { pipe } from 'fp-ts/function' import * as O from 'fp-ts/Option' import * as TE from 'fp-ts/TaskEither' import { capDelay, exponentialBackoff, limitRetries, Monoid, RetryStatus } from 'retry-ts' import { retrying } from 'retry-ts/Task' // Define retry policy: exponential backoff with cap and limit const policy = capDelay(2000, Monoid.concat(exponentialBackoff(200), limitRetries(5))) // Simulated API that always fails const fakeAPI = TE.left('API errored out') // Log function that displays retry delays const logDelay = (status: RetryStatus) => TE.rightIO( log( pipe( status.previousDelay, O.map((delay) => `retrying in ${delay} milliseconds...`), O.getOrElse(() => 'first attempt...') ) ) ) ) // Retry the API call, logging delays, continue while result is Left const result = retrying( policy, (status) => pipe(logDelay(status), TE.apSecond(fakeAPI)), E.isLeft ) result().then((e) => console.log(e)) // Output: // first attempt... // retrying in 200 milliseconds... // retrying in 400 milliseconds... // retrying in 800 milliseconds... // retrying in 1600 milliseconds... // retrying in 2000 milliseconds... // left("API errored out") ``` -------------------------------- ### Retry Status Tracking and Policy Application Source: https://context7.com/gcanti/retry-ts/llms.txt Illustrates the usage of the RetryStatus interface and related functions from retry-ts. It shows how to initialize retry status, apply different retry policies (like exponential backoff), and observe the cumulative delay and previous delay updates across multiple retry attempts. ```typescript import { RetryStatus, defaultRetryStatus, applyPolicy, exponentialBackoff } from 'retry-ts' import * as O from 'fp-ts/Option' // Initial status console.log(defaultRetryStatus) // { // iterNumber: 0, // cumulativeDelay: 0, // previousDelay: none // } const policy = exponentialBackoff(100) // Track status through multiple retries let status: RetryStatus = defaultRetryStatus status = applyPolicy(policy, status) console.log(status) // { // iterNumber: 1, // cumulativeDelay: 100, // previousDelay: some(100) // } status = applyPolicy(policy, status) console.log(status) // { // iterNumber: 2, // cumulativeDelay: 300, // 100 + 200 // previousDelay: some(200) // } status = applyPolicy(policy, status) console.log(status) // { // iterNumber: 3, // cumulativeDelay: 700, // 100 + 200 + 400 // previousDelay: some(400) // } ``` -------------------------------- ### Apply Policy and Delay in ReaderTask Context Source: https://context7.com/gcanti/retry-ts/llms.txt Demonstrates how to apply a retry policy and introduce a delay within a ReaderTask context using retry-ts. It requires an environment configuration and returns a function that, when executed, applies the policy and returns the updated retry status. ```typescript import { pipe } from 'fp-ts/function' import * as RT from 'fp-ts/ReaderTask' import { exponentialBackoff, defaultRetryStatus } from 'retry-ts' import { applyAndDelay } from 'retry-ts/ReaderTask' interface Env { logEnabled: boolean } const policy = exponentialBackoff(100) const delayedStatusReader = applyAndDelay(policy, defaultRetryStatus) const env: Env = { logEnabled: true } delayedStatusReader(env)().then((status) => { console.log(`Applied policy with delay: ${status.previousDelay}`) }) ``` -------------------------------- ### Monoid Retry Policy Combination (TypeScript) Source: https://github.com/gcanti/retry-ts/blob/master/docs/modules/index.ts.md Demonstrates how to combine multiple RetryPolicy strategies using the Monoid instance. The combined policy returns 'None' if either individual policy returns 'None', and uses the larger delay if both return a delay. This allows for flexible creation of complex retry behaviors. ```typescript import { monoidRetryPolicy, exponentialBackoff, limitRetries } from 'retry-ts' // One can easily define an exponential backoff policy with a limited // number of retries: export const limitedBackoff = monoidRetryPolicy.concat(exponentialBackoff(50), limitRetries(5)) ``` -------------------------------- ### Retry Policy with Exponential Backoff and Capped Delay in TypeScript Source: https://github.com/gcanti/retry-ts/blob/master/docs/index.md Demonstrates how to create a retry policy using `retry-ts`. This policy combines exponential backoff with a maximum delay cap and a limit on the number of retries. It's suitable for handling API errors or other transient failures. ```TypeScript import { log } from 'fp-ts/Console' import * as E from 'fp-ts/Either' import { pipe } from 'fp-ts/function' import * as O from 'fp-ts/Option' import * as TE from 'fp-ts/TaskEither' import { capDelay, exponentialBackoff, limitRetries, Monoid, RetryStatus } from 'retry-ts' import { retrying } from 'retry-ts/Task' const policy = capDelay(2000, Monoid.concat(exponentialBackoff(200), limitRetries(5))) const fakeAPI = TE.left('API errored out') const logDelay = (status: RetryStatus) => TE.rightIO( log( pipe( status.previousDelay, O.map((delay) => `retrying in ${delay} milliseconds...`), O.getOrElse(() => 'first attempt...')) ) ) const result = retrying(policy, (status) => pipe(logDelay(status), TE.apSecond(fakeAPI)), E.isLeft) result().then((e) => console.log(e)) ``` -------------------------------- ### Exponential Backoff Policy (TypeScript) Source: https://github.com/gcanti/retry-ts/blob/master/docs/modules/index.ts.md Creates a RetryPolicy that increases the delay exponentially with each retry attempt. The delay doubles after each iteration, providing a common strategy for handling temporary network issues. ```typescript export declare function exponentialBackoff(delay: number): RetryPolicy ``` -------------------------------- ### Apply and Delay Retry Policy with ReaderTask Source: https://github.com/gcanti/retry-ts/blob/master/docs/modules/ReaderTask.ts.md The applyAndDelay function applies a given RetryPolicy to a RetryStatus and delays execution if a retry is indicated. It returns the updated status. This function is part of the retry-ts library and operates within a ReaderTask environment. ```typescript export declare const applyAndDelay: (policy: RetryPolicy, status: RetryStatus) => ReaderTask ``` -------------------------------- ### Combine Retry Policies with Monoid in TypeScript Source: https://context7.com/gcanti/retry-ts/llms.txt Demonstrates using the Monoid.concat function to combine multiple retry policies, such as exponential backoff, retry limits, and delay capping. The combined policy uses the largest delay if both return one, and returns none if either policy returns none. It requires importing Monoid, exponentialBackoff, limitRetries, and capDelay from 'retry-ts'. ```typescript import { Monoid, exponentialBackoff, limitRetries, capDelay } from 'retry-ts' // Combine exponential backoff with retry limit const policy1 = Monoid.concat( exponentialBackoff(100), limitRetries(5) ) // More complex: exponential backoff, capped, and limited const policy2 = capDelay( 2000, Monoid.concat( exponentialBackoff(200), limitRetries(5) ) ) // The combined policy will: // - Use exponential backoff starting at 200ms // - Cap any delay at 2000ms maximum // - Stop after 5 retry attempts ``` -------------------------------- ### Default Retry Status (TypeScript) Source: https://github.com/gcanti/retry-ts/blob/master/docs/modules/index.ts.md Provides the initial, default RetryStatus object. This is primarily intended for use in testing custom retry handlers and policies. ```typescript export declare const defaultRetryStatus: RetryStatus ``` -------------------------------- ### Task Retry with Successful Recovery in TypeScript Source: https://context7.com/gcanti/retry-ts/llms.txt Illustrates a Task-based action that eventually succeeds after several retries. The 'unstableAPI' function is designed to fail a few times before returning a success. The 'retrying' function is used with a constant delay policy to repeatedly call this API until it succeeds or the retry limit is reached. Dependencies include 'fp-ts' (Either, TaskEither) and 'retry-ts' (constantDelay, limitRetries, Monoid). ```typescript import * as E from 'fp-ts/Either' import * as TE from 'fp-ts/TaskEither' import { constantDelay, limitRetries, Monoid } from 'retry-ts' import { retrying } from 'retry-ts/Task' let attemptCount = 0 // API that succeeds on 3rd attempt const unstableAPI = TE.fromIO(() => { attemptCount++ if (attemptCount < 3) { return E.left(`Attempt ${attemptCount} failed`) } return E.right('Success!') }) const policy = Monoid.concat(constantDelay(100), limitRetries(5)) const result = retrying( policy, () => unstableAPI, E.isLeft // Keep retrying while result is Left ) result().then((outcome) => { console.log(outcome) // right("Success!") console.log(`Succeeded after ${attemptCount} attempts`) }) ``` -------------------------------- ### Limit Retries Policy (TypeScript) Source: https://github.com/gcanti/retry-ts/blob/master/docs/modules/index.ts.md Generates a RetryPolicy that allows retrying immediately up to a specified number of times. After the limit is reached, subsequent attempts will fail. ```typescript export declare function limitRetries(i: number): RetryPolicy ``` -------------------------------- ### Apply Retry Policy (TypeScript) Source: https://github.com/gcanti/retry-ts/blob/master/docs/modules/index.ts.md A function to apply a given RetryPolicy to a RetryStatus to determine the outcome (delay or failure). It takes a policy and the current status, returning the updated status. ```typescript export declare function applyPolicy(policy: RetryPolicy, status: RetryStatus): RetryStatus ``` -------------------------------- ### Retrying Combinator for Non-Exception Failures (TypeScript) Source: https://github.com/gcanti/retry-ts/blob/master/docs/modules/Task.ts.md A combinator for retrying actions that signal failure in their return type (e.g., Option, Either) rather than throwing exceptions. It takes a RetryPolicy, an action function that accepts RetryStatus, and a check function to determine if a retry is needed. ```typescript export declare function retrying( policy: RetryPolicy, action: (status: RetryStatus) => T.Task, check: (a: A) => boolean ): T.Task ``` -------------------------------- ### RetryStatus Interface (TypeScript) Source: https://github.com/gcanti/retry-ts/blob/master/docs/modules/index.ts.md Defines the RetryStatus interface, which tracks the state of a retry attempt. It includes the current iteration number, cumulative delay, and the delay of the previous attempt. ```typescript export interface RetryStatus { /** Iteration number, where `0` is the first try */ iterNumber: number /** Delay incurred so far from retries */ cumulativeDelay: number /** Latest attempt's delay. Will always be `none` on first run. */ previousDelay: O.Option } ``` -------------------------------- ### Apply Retry Policy and Delay (TypeScript) Source: https://github.com/gcanti/retry-ts/blob/master/docs/modules/Task.ts.md Applies a given RetryPolicy to a RetryStatus and delays execution if a retry is indicated. Returns the updated status. This function is part of the 'utils' in the Task module. ```typescript export declare function applyAndDelay(policy: RetryPolicy, status: RetryStatus): T.Task ``` -------------------------------- ### RetryPolicy Interface (TypeScript) Source: https://github.com/gcanti/retry-ts/blob/master/docs/modules/index.ts.md Defines the RetryPolicy interface, a function that takes RetryStatus and returns an Option representing the delay in milliseconds. A return value of 'None' indicates that the retry limit has been reached. ```typescript export interface RetryPolicy { (status: RetryStatus): O.Option } ``` -------------------------------- ### Constant Delay Retry Policy in TypeScript Source: https://context7.com/gcanti/retry-ts/llms.txt Creates a retry policy that uses a fixed delay between all retry attempts. This policy is simple and predictable, suitable when a consistent waiting period is desired. It allows for unlimited retries unless combined with other limiting policies. ```typescript import { constantDelay, applyPolicy, defaultRetryStatus } from 'retry-ts' // Retry with constant 500ms delay const policy = constantDelay(500) let status = defaultRetryStatus for (let i = 0; i < 3; i++) { status = applyPolicy(policy, status) console.log(`Retry ${status.iterNumber}: delay=${status.previousDelay}`) } // Output: // Retry 1: delay=some(500) // Retry 2: delay=some(500) // Retry 3: delay=some(500) ``` -------------------------------- ### Cap Delay Policy in TypeScript Source: https://context7.com/gcanti/retry-ts/llms.txt Combines another retry policy with a maximum delay limit. This prevents delays from growing excessively large, especially when used with policies like exponential backoff. It ensures that even after many retries, the delay does not exceed a specified threshold. ```typescript import { capDelay, exponentialBackoff, applyPolicy, defaultRetryStatus } from 'retry-ts' // Exponential backoff but capped at 1000ms const policy = capDelay(1000, exponentialBackoff(200)) let status = defaultRetryStatus for (let i = 0; i < 5; i++) { status = applyPolicy(policy, status) const delay = status.previousDelay console.log(`Retry ${status.iterNumber}: ${delay}ms`) } // Output: // Retry 1: some(200)ms - 200 * 2^0 // Retry 2: some(400)ms - 200 * 2^1 // Retry 3: some(800)ms - 200 * 2^2 // Retry 4: some(1000)ms - 200 * 2^3 = 1600, capped to 1000 // Retry 5: some(1000)ms - 200 * 2^4 = 3200, capped to 1000 ``` -------------------------------- ### Constant Delay Policy (TypeScript) Source: https://github.com/gcanti/retry-ts/blob/master/docs/modules/index.ts.md Generates a RetryPolicy that always returns a constant delay value, with no limit on the number of retries. This is useful for simple retry strategies where the delay should remain consistent. ```typescript export declare function constantDelay(delay: number): RetryPolicy ``` -------------------------------- ### Limit Retries by Delay Policy (TypeScript) Source: https://github.com/gcanti/retry-ts/blob/master/docs/modules/index.ts.md Creates a RetryPolicy that stops retrying once the delay per try reaches or exceeds a specified maximum delay. This provides a way to fail fast if individual retry delays become too long. ```typescript export declare function limitRetriesByDelay(maxDelay: number, policy: RetryPolicy): RetryPolicy ``` -------------------------------- ### Retry Combinator for Non-Exception Failures in ReaderTask Source: https://github.com/gcanti/retry-ts/blob/master/docs/modules/ReaderTask.ts.md The retrying function acts as a combinator for actions that signal failure within their type, such as Option or Either, instead of throwing exceptions. It retries the action based on a RetryPolicy and a check function to determine retryable outcomes. This is useful for managing retries in ReaderTask with custom failure types. ```typescript export declare function retrying( policy: RetryPolicy, action: (status: RetryStatus) => ReaderTask, check: (a: A) => boolean ): ReaderTask ``` -------------------------------- ### Cap Delay Policy (TypeScript) Source: https://github.com/gcanti/retry-ts/blob/master/docs/modules/index.ts.md Creates a new RetryPolicy that caps the maximum delay returned by an existing policy. This function does not terminate retries on its own; it only limits the delay duration per retry. To ensure termination, it should be combined with retry limiting functions. ```typescript export declare function capDelay(maxDelay: number, policy: RetryPolicy): RetryPolicy ``` -------------------------------- ### Monoid Retry Policy Alias (TypeScript) Source: https://github.com/gcanti/retry-ts/blob/master/docs/modules/index.ts.md An alias for the Monoid instance for RetryPolicy, intended to be used with the 'concat' method for combining policies. It is recommended to use the 'Monoid' export directly. ```typescript export declare const monoidRetryPolicy: M.Monoid ``` -------------------------------- ### Limit Retries Policy in TypeScript Source: https://context7.com/gcanti/retry-ts/llms.txt Implements a retry policy that stops retrying after a maximum number of attempts. This prevents infinite retry loops and ensures operations eventually fail if they don't succeed within a set number of tries. It uses 'applyPolicy' to check the retry limit against the current iteration number. ```typescript import { limitRetries, applyPolicy, defaultRetryStatus } from 'retry-ts' import * as O from 'fp-ts/Option' // Allow maximum of 3 retries const policy = limitRetries(3) // Apply policy and track iterations let status = defaultRetryStatus for (let i = 0; i < 5; i++) { status = applyPolicy(policy, status) console.log(`Iteration ${status.iterNumber}: ${O.isSome(status.previousDelay) ? 'retry' : 'stop'}`) } // Output: // Iteration 1: retry // Iteration 2: retry // Iteration 3: retry // Iteration 4: stop // Iteration 5: stop ``` -------------------------------- ### Limit Retries By Delay Policy in TypeScript Source: https://context7.com/gcanti/retry-ts/llms.txt Stops retrying if the calculated delay for a specific attempt would exceed a given threshold. This is useful for preventing excessively long waits for retries, even if the underlying policy (like exponential backoff) would suggest a longer duration. ```typescript import { limitRetriesByDelay, exponentialBackoff, applyPolicy, defaultRetryStatus } from 'retry-ts' import * as O from 'fp-ts/Option' // Stop when delay would exceed 500ms const policy = limitRetriesByDelay(500, exponentialBackoff(100)) let status = defaultRetryStatus for (let i = 0; i < 5; i++) { status = applyPolicy(policy, status) if (O.isSome(status.previousDelay)) { console.log(`Retry ${status.iterNumber}: ${status.previousDelay.value}ms`) } else { console.log(`Retry ${status.iterNumber}: stopped (delay exceeded threshold)`) } } // Output: // Retry 1: 100ms - 100 * 2^0 = 100 // Retry 2: 200ms - 100 * 2^1 = 200 // Retry 3: 400ms - 100 * 2^2 = 400 // Retry 4: stopped (delay exceeded threshold) - 100 * 2^3 = 800 > 500 // Retry 5: stopped (delay exceeded threshold) ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.