@glxalokesh/retri 1.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +141 -0
- package/package.json +49 -0
- package/src/backoff.js +24 -0
- package/src/constants.js +0 -0
- package/src/delay.js +16 -0
- package/src/error.js +21 -0
- package/src/index.js +2 -0
- package/src/jitter.js +12 -0
- package/src/retry.js +77 -0
- package/src/retryContext.js +12 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Alokesh Maitra
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
ADDED
|
@@ -0,0 +1,141 @@
|
|
|
1
|
+
# retri
|
|
2
|
+

|
|
3
|
+

|
|
4
|
+

|
|
5
|
+
|
|
6
|
+
A lightweight, configurable retry utility for async JavaScript. Features built-in support for backoff strategies, jitter, lifecycle hooks, and abort signals.
|
|
7
|
+
|
|
8
|
+
## Features
|
|
9
|
+
|
|
10
|
+
- **Configurable retries**: Set max attempts, delay, and custom retry logic.
|
|
11
|
+
- **Backoff strategies**: Built-in support for `fixed`, `linear`, and `exponential` backoff.
|
|
12
|
+
- **Jitter**: Add randomness to delays to prevent thundering herd problems.
|
|
13
|
+
- **Lifecycle Hooks**: Track execution using `onSuccess`, `onFail`, and `onRetry` callbacks.
|
|
14
|
+
- **Abort controller support**: Cancel pending retries seamlessly using an `AbortSignal`.
|
|
15
|
+
- **Custom retry logic**: Determine dynamically whether an error is retryable using `shouldRetry`.
|
|
16
|
+
|
|
17
|
+
## Installation
|
|
18
|
+
|
|
19
|
+
```bash
|
|
20
|
+
npm install @glxalokesh/retri
|
|
21
|
+
```
|
|
22
|
+
|
|
23
|
+
## Usage
|
|
24
|
+
|
|
25
|
+
### Basic Usage
|
|
26
|
+
|
|
27
|
+
```javascript
|
|
28
|
+
import { retry } from 'retri';
|
|
29
|
+
|
|
30
|
+
async function fetchData() {
|
|
31
|
+
const response = await fetch('https://api.example.com/data');
|
|
32
|
+
if (!response.ok) throw new Error('Network error');
|
|
33
|
+
return response.json();
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
// Retries up to 3 times (4 attempts total) with a fixed delay of 300ms
|
|
37
|
+
const data = await retry(fetchData);
|
|
38
|
+
```
|
|
39
|
+
|
|
40
|
+
### Advanced Usage with Options
|
|
41
|
+
|
|
42
|
+
```javascript
|
|
43
|
+
import { retry } from 'retri';
|
|
44
|
+
|
|
45
|
+
const abortController = new AbortController();
|
|
46
|
+
|
|
47
|
+
const options = {
|
|
48
|
+
retries: 5, // Number of retry attempts (default: 3)
|
|
49
|
+
delay: 500, // Initial delay in ms (default: 300)
|
|
50
|
+
backoff: 'exponential', // Backoff strategy: 'fixed', 'linear', or 'exponential' (default: 'fixed')
|
|
51
|
+
factor: 2, // Multiplier for exponential backoff (default: 2)
|
|
52
|
+
jitter: 0.2, // Jitter fraction (e.g., 0.2 means +/- 20% randomness)
|
|
53
|
+
signal: abortController.signal, // Pass an AbortSignal to cancel early
|
|
54
|
+
|
|
55
|
+
// Only retry on specific errors
|
|
56
|
+
shouldRetry: (error, ctx) => {
|
|
57
|
+
if (error.message.includes('Fatal')) return false; // Stop retrying
|
|
58
|
+
return true;
|
|
59
|
+
},
|
|
60
|
+
|
|
61
|
+
// Lifecycle hooks
|
|
62
|
+
onRetry: (ctx) => console.log(`Retrying... attempt ${ctx.attempt}. Errors left: ${ctx.retriesLeft}`),
|
|
63
|
+
onSuccess: (ctx) => console.log(`Success on attempt ${ctx.attempt}! Time elapsed: ${ctx.timeElapsed}ms`),
|
|
64
|
+
onFail: (ctx) => console.error(`Failed after ${ctx.attempt} attempts.`)
|
|
65
|
+
};
|
|
66
|
+
|
|
67
|
+
try {
|
|
68
|
+
const result = await retry(fetchData, options);
|
|
69
|
+
} catch (error) {
|
|
70
|
+
console.error('Operation failed:', error);
|
|
71
|
+
}
|
|
72
|
+
```
|
|
73
|
+
|
|
74
|
+
## API Reference
|
|
75
|
+
|
|
76
|
+
### `retry(fn, options?)`
|
|
77
|
+
|
|
78
|
+
Executes the async function `fn` and automatically retries it upon failure according to the provided `options`.
|
|
79
|
+
|
|
80
|
+
#### Arguments
|
|
81
|
+
|
|
82
|
+
- `fn` *(Function)*: An asynchronous function that returns a Promise.
|
|
83
|
+
- `options` *(Object)*: Configuration options (optional).
|
|
84
|
+
|
|
85
|
+
#### Options Available
|
|
86
|
+
|
|
87
|
+
| Option | Type | Default | Description |
|
|
88
|
+
| --- | --- | --- | --- |
|
|
89
|
+
| `retries` | `number` | `3` | Maximum number of **retries** (total attempts will be `retries + 1`). |
|
|
90
|
+
| `delay` | `number` | `300` | Initial delay between attempts, in milliseconds. |
|
|
91
|
+
| `backoff` | `string` | `'fixed'` | Strategy for calculating delay: `'fixed'`, `'linear'`, or `'exponential'`. |
|
|
92
|
+
| `factor` | `number` | `2` | Multiplier used when `backoff` is `'exponential'`. |
|
|
93
|
+
| `jitter` | `number` | `0` | Fraction (`0` to `1`) of jitter to apply to the delay. `0.2` adds ±20% randomness. |
|
|
94
|
+
| `signal` | `AbortSignal` | `null` | Used to abort the retry process entirely. Throws a `DOMException` error. |
|
|
95
|
+
| `shouldRetry` | `Function`| `() => true`| Predicate function `(error, context)` returning a boolean. If `false`, retries are aborted. |
|
|
96
|
+
| `onSuccess` | `Function`| `-` | Hook executed when `fn` completes successfully. |
|
|
97
|
+
| `onRetry` | `Function`| `-` | Hook executed right before a retry wait period begins. |
|
|
98
|
+
| `onFail` | `Function`| `-` | Hook executed when all retries are exhausted or `shouldRetry` returns false. |
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
### Context Object (`ctx`)
|
|
102
|
+
|
|
103
|
+
Lifecycle hooks (`onSuccess`, `onRetry`, `onFail`) and the `shouldRetry` predicate receive a context object with useful properties:
|
|
104
|
+
|
|
105
|
+
- `ctx.attempt`: The current attempt number (starts at 1).
|
|
106
|
+
- `ctx.retriesLeft`: Number of remaining allowed retries.
|
|
107
|
+
- `ctx.timeElapsed`: Milliseconds elapsed since the primary execution started.
|
|
108
|
+
- `ctx.error`: The most recent error encountered (is `null` in `onSuccess`).
|
|
109
|
+
- `ctx.result`: The returned result (only available in `onSuccess`).
|
|
110
|
+
- `ctx.errors`: An array of all errors encountered so far (available in `onFail`).
|
|
111
|
+
|
|
112
|
+
### Errors
|
|
113
|
+
|
|
114
|
+
When exceptions bubble out of the `retry` utility, they might be custom Error classes depending on the reason:
|
|
115
|
+
|
|
116
|
+
- **`RetriError`**: Thrown when maximum retries are exceeded or if `shouldRetry` returns false. Contains properties `.attempt`, `.errors` (array of all caught errors), and `.lastError`.
|
|
117
|
+
- **`DOMException`**: Standard DOMException with name `"AbortError"` is thrown when the provided `AbortSignal` is aborted.
|
|
118
|
+
## Contributing
|
|
119
|
+
|
|
120
|
+
retri is an **open-source project**, and contributions are welcome.
|
|
121
|
+
|
|
122
|
+
- Found a bug? → Open an issue
|
|
123
|
+
- Have a feature idea? → Start a discussion
|
|
124
|
+
- Want to improve code or docs? → Open a pull request
|
|
125
|
+
|
|
126
|
+
GitHub Repository:
|
|
127
|
+
👉 **https://github.com/GLXALOKESH/retri**
|
|
128
|
+
|
|
129
|
+
The issue tracker is open to everyone — no contribution is too small.
|
|
130
|
+
## Stability & Versioning
|
|
131
|
+
|
|
132
|
+
retri follows semantic versioning:
|
|
133
|
+
|
|
134
|
+
- **PATCH**: Bug fixes
|
|
135
|
+
- **MINOR**: New features (may introduce new options)
|
|
136
|
+
- **MAJOR**: Breaking changes (will be clearly documented)
|
|
137
|
+
|
|
138
|
+
Breaking changes will be avoided where possible and clearly announced.
|
|
139
|
+
## License
|
|
140
|
+
|
|
141
|
+
MIT
|
package/package.json
ADDED
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@glxalokesh/retri",
|
|
3
|
+
"version": "1.0.1",
|
|
4
|
+
"publishConfig": {
|
|
5
|
+
"access": "public"
|
|
6
|
+
},
|
|
7
|
+
"description": "A lightweight, configurable retry utility for async JavaScript with backoff, jitter, hooks, and abort support",
|
|
8
|
+
"main": "src/index.js",
|
|
9
|
+
"exports": {
|
|
10
|
+
".": "./src/index.js"
|
|
11
|
+
},
|
|
12
|
+
"files": [
|
|
13
|
+
"src",
|
|
14
|
+
"README.md",
|
|
15
|
+
"LICENSE"
|
|
16
|
+
],
|
|
17
|
+
"directories": {
|
|
18
|
+
"doc": "docs",
|
|
19
|
+
"test": "test"
|
|
20
|
+
},
|
|
21
|
+
"scripts": {
|
|
22
|
+
"test": "vitest",
|
|
23
|
+
"prepublishOnly": "npm test -- --run"
|
|
24
|
+
},
|
|
25
|
+
"type": "module",
|
|
26
|
+
"sideEffects": false,
|
|
27
|
+
"engines": {
|
|
28
|
+
"node": ">=18"
|
|
29
|
+
},
|
|
30
|
+
"repository": {
|
|
31
|
+
"type": "git",
|
|
32
|
+
"url": "git+https://github.com/GLXALOKESH/retri.git"
|
|
33
|
+
},
|
|
34
|
+
"keywords": [
|
|
35
|
+
"retry",
|
|
36
|
+
"async",
|
|
37
|
+
"promise",
|
|
38
|
+
"util"
|
|
39
|
+
],
|
|
40
|
+
"author": "alokesh maitra",
|
|
41
|
+
"license": "MIT",
|
|
42
|
+
"bugs": {
|
|
43
|
+
"url": "https://github.com/GLXALOKESH/retri/issues"
|
|
44
|
+
},
|
|
45
|
+
"homepage": "https://github.com/GLXALOKESH/retri#readme",
|
|
46
|
+
"devDependencies": {
|
|
47
|
+
"vitest": "^4.0.18"
|
|
48
|
+
}
|
|
49
|
+
}
|
package/src/backoff.js
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
|
|
2
|
+
|
|
3
|
+
async function backoff(type, delay, attempt, factor) {
|
|
4
|
+
|
|
5
|
+
attempt = attempt ? attempt : 0;
|
|
6
|
+
factor = factor ? factor : 2;
|
|
7
|
+
|
|
8
|
+
if (type === "fixed") {
|
|
9
|
+
|
|
10
|
+
return delay;
|
|
11
|
+
}
|
|
12
|
+
else if (type === "linear") {
|
|
13
|
+
|
|
14
|
+
return delay * attempt;
|
|
15
|
+
}
|
|
16
|
+
else if (type === "exponential") {
|
|
17
|
+
return delay * factor ^ (attempt - 1);
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
export { backoff }
|
package/src/constants.js
ADDED
|
File without changes
|
package/src/delay.js
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
function delay(ms, signal) {
|
|
2
|
+
return new Promise((resolve, reject) => {
|
|
3
|
+
if (signal?.aborted) {
|
|
4
|
+
return reject(new DOMException("Aborted", "AbortError"));
|
|
5
|
+
}
|
|
6
|
+
|
|
7
|
+
const timer = setTimeout(resolve, ms);
|
|
8
|
+
|
|
9
|
+
signal?.addEventListener("abort", () => {
|
|
10
|
+
clearTimeout(timer);
|
|
11
|
+
reject(new DOMException("Aborted", "AbortError"));
|
|
12
|
+
}, { once: true });
|
|
13
|
+
});
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
export { delay };
|
package/src/error.js
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
export class RetriError extends Error {
|
|
2
|
+
|
|
3
|
+
constructor(message, attempt, errors) {
|
|
4
|
+
super(message);
|
|
5
|
+
this.name = 'RetriError';
|
|
6
|
+
this.attempt = attempt;
|
|
7
|
+
this.errors = errors;
|
|
8
|
+
this.lastError = errors[errors.length - 1];
|
|
9
|
+
}
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
export class AbortError extends Error {
|
|
13
|
+
|
|
14
|
+
constructor(message, attempt, errors) {
|
|
15
|
+
super(message);
|
|
16
|
+
this.name = 'AbortError';
|
|
17
|
+
this.attempt = attempt;
|
|
18
|
+
this.errors = errors;
|
|
19
|
+
this.lastError = errors[errors.length - 1];
|
|
20
|
+
}
|
|
21
|
+
}
|
package/src/index.js
ADDED
package/src/jitter.js
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
|
|
2
|
+
|
|
3
|
+
async function jitter(delay, fraction) {
|
|
4
|
+
const jitterAmount = delay * fraction;
|
|
5
|
+
const min = delay - jitterAmount;
|
|
6
|
+
const max = delay + jitterAmount;
|
|
7
|
+
const result = Math.random() * (max - min) + min;
|
|
8
|
+
|
|
9
|
+
return result;
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
export { jitter }
|
package/src/retry.js
ADDED
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
import { RetriError, AbortError } from "./error.js";
|
|
2
|
+
import { delay } from "./delay.js";
|
|
3
|
+
import { backoff } from "./backoff.js";
|
|
4
|
+
import { jitter } from "./jitter.js";
|
|
5
|
+
import { createContext } from "./retryContext.js";
|
|
6
|
+
|
|
7
|
+
async function retry(fn, options = {}) {
|
|
8
|
+
const retries = options.retries ?? 3;
|
|
9
|
+
const errors = [];
|
|
10
|
+
const delayms = options.delay ?? 300;
|
|
11
|
+
const backoffSelection = options.backoff ?? "fixed"
|
|
12
|
+
let currentDelay = delayms;
|
|
13
|
+
const factor = options.factor ?? 2;
|
|
14
|
+
const jitterVal = options.jitter ?? 0;
|
|
15
|
+
const maxAttempts = retries + 1;
|
|
16
|
+
let currentDelaywithJitter = currentDelay;
|
|
17
|
+
const startTime = Date.now();
|
|
18
|
+
const signal = options?.signal ?? null
|
|
19
|
+
function runHooks(hook, payload) {
|
|
20
|
+
try {
|
|
21
|
+
hook?.(payload);
|
|
22
|
+
} catch (error) {
|
|
23
|
+
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
function throwIfAborted() {
|
|
28
|
+
if (signal?.aborted) {
|
|
29
|
+
throw new DOMException("Aborted", "AbortError");
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
for (let attempt = 1; attempt <= maxAttempts; attempt++) {
|
|
34
|
+
throwIfAborted();
|
|
35
|
+
try {
|
|
36
|
+
const result = await fn();
|
|
37
|
+
const ctx = createContext({ attempt, retries, startTime, error: null })
|
|
38
|
+
runHooks(options.onSuccess, { ...ctx, result });
|
|
39
|
+
return result;
|
|
40
|
+
} catch (error) {
|
|
41
|
+
errors.push(error);
|
|
42
|
+
|
|
43
|
+
const ctx = createContext({ attempt, retries, startTime, error })
|
|
44
|
+
const allowretry = options.shouldRetry ? options.shouldRetry(error, ctx) : true;
|
|
45
|
+
if (allowretry != true || attempt === maxAttempts) {
|
|
46
|
+
runHooks(options.onFail, { ...ctx, errors });
|
|
47
|
+
if (attempt === maxAttempts) {
|
|
48
|
+
throw new RetriError("Maximum Retries Exceeded", attempt, errors);
|
|
49
|
+
}
|
|
50
|
+
throw new RetriError("Error not allowed to retry", attempt, errors);
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
runHooks(options.onRetry, { ...ctx })
|
|
54
|
+
|
|
55
|
+
if (jitterVal) {
|
|
56
|
+
currentDelaywithJitter = await jitter(currentDelay, jitterVal);
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
await delay(currentDelaywithJitter, signal);
|
|
62
|
+
if (backoffSelection === "fixed") {
|
|
63
|
+
currentDelay = await backoff(backoffSelection, delayms)
|
|
64
|
+
}
|
|
65
|
+
else if (backoffSelection === "linear") {
|
|
66
|
+
currentDelay = await backoff(backoffSelection, delayms, attempt + 1)
|
|
67
|
+
}
|
|
68
|
+
else if (backoffSelection === "exponential") {
|
|
69
|
+
|
|
70
|
+
currentDelay = await backoff(backoffSelection, delayms, attempt, factor)
|
|
71
|
+
}
|
|
72
|
+
throwIfAborted();
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
export { retry }
|