@cedvict/http-guardian-plugin-retry 0.0.1-next.10
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/CHANGELOG.md +5 -0
- package/LICENSE +21 -0
- package/README.md +9 -0
- package/dist/index.cjs +77 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +29 -0
- package/dist/index.d.ts +29 -0
- package/dist/index.js +75 -0
- package/dist/index.js.map +1 -0
- package/package.json +58 -0
package/CHANGELOG.md
ADDED
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Cedvict
|
|
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
package/dist/index.cjs
ADDED
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
// src/index.ts
|
|
4
|
+
var META_KEY = /* @__PURE__ */ Symbol.for("http-guardian.retry");
|
|
5
|
+
function sleep(ms) {
|
|
6
|
+
return new Promise((r) => setTimeout(r, ms));
|
|
7
|
+
}
|
|
8
|
+
function parseRetryAfterMs(h, nowMs) {
|
|
9
|
+
const v = h.get("retry-after");
|
|
10
|
+
if (!v) return void 0;
|
|
11
|
+
const asInt = Number(v);
|
|
12
|
+
if (Number.isFinite(asInt)) return Math.max(0, asInt * 1e3);
|
|
13
|
+
const asDate = Date.parse(v);
|
|
14
|
+
if (!Number.isNaN(asDate)) return Math.max(0, asDate - nowMs);
|
|
15
|
+
return void 0;
|
|
16
|
+
}
|
|
17
|
+
function isIdempotent(method) {
|
|
18
|
+
return method === "GET" || method === "HEAD" || method === "OPTIONS";
|
|
19
|
+
}
|
|
20
|
+
function backoffDelayMs(attempt, base, max, jitter) {
|
|
21
|
+
const exp = Math.min(max, base * Math.pow(2, attempt - 1));
|
|
22
|
+
if (jitter === "full") return Math.floor(Math.random() * exp);
|
|
23
|
+
return exp;
|
|
24
|
+
}
|
|
25
|
+
function retryPlugin(options = {}) {
|
|
26
|
+
const retries = options.retries ?? 3;
|
|
27
|
+
const baseDelayMs = options.baseDelayMs ?? 200;
|
|
28
|
+
const maxDelayMs = options.maxDelayMs ?? 5e3;
|
|
29
|
+
const jitter = options.jitter ?? "full";
|
|
30
|
+
const retryOnStatuses = options.retryOnStatuses ?? [408, 429, 500, 502, 503, 504];
|
|
31
|
+
const retryOnNetworkError = options.retryOnNetworkError ?? true;
|
|
32
|
+
const isRetryableRequest = options.isRetryableRequest ?? ((ctx) => isIdempotent(ctx.method));
|
|
33
|
+
const wait = options.wait ?? ((ms) => sleep(ms));
|
|
34
|
+
const guard = async (ctx, next) => {
|
|
35
|
+
if (!isRetryableRequest(ctx)) return next(ctx);
|
|
36
|
+
const meta = ctx[META_KEY] ??= { attempt: 0 };
|
|
37
|
+
while (true) {
|
|
38
|
+
let res;
|
|
39
|
+
let networkError;
|
|
40
|
+
try {
|
|
41
|
+
res = await next(ctx);
|
|
42
|
+
} catch (e) {
|
|
43
|
+
networkError = e;
|
|
44
|
+
}
|
|
45
|
+
const shouldRetryNetwork = !!networkError && retryOnNetworkError;
|
|
46
|
+
const shouldRetryStatus = !!res && retryOnStatuses.includes(res.status);
|
|
47
|
+
if (!shouldRetryNetwork && !shouldRetryStatus) {
|
|
48
|
+
if (networkError) throw networkError;
|
|
49
|
+
return res;
|
|
50
|
+
}
|
|
51
|
+
if (meta.attempt >= retries) {
|
|
52
|
+
if (networkError) throw networkError;
|
|
53
|
+
return res;
|
|
54
|
+
}
|
|
55
|
+
meta.attempt += 1;
|
|
56
|
+
const now = Date.now();
|
|
57
|
+
let delay = backoffDelayMs(meta.attempt, baseDelayMs, maxDelayMs, jitter);
|
|
58
|
+
if (res) {
|
|
59
|
+
const ra = parseRetryAfterMs(res.headers, now);
|
|
60
|
+
if (typeof ra === "number") delay = Math.min(maxDelayMs, Math.max(delay, ra));
|
|
61
|
+
}
|
|
62
|
+
await wait(delay, ctx);
|
|
63
|
+
ctx = Object.assign({}, ctx, { attempt: ctx.attempt + 1 });
|
|
64
|
+
ctx[META_KEY] = meta;
|
|
65
|
+
}
|
|
66
|
+
};
|
|
67
|
+
return {
|
|
68
|
+
name: "retry",
|
|
69
|
+
apply: (draft) => {
|
|
70
|
+
draft.guards = [...draft.guards ?? [], guard];
|
|
71
|
+
}
|
|
72
|
+
};
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
exports.retryPlugin = retryPlugin;
|
|
76
|
+
//# sourceMappingURL=index.cjs.map
|
|
77
|
+
//# sourceMappingURL=index.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/index.ts"],"names":[],"mappings":";;;AAuBA,IAAM,QAAA,mBA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,IAAsB,CAAC,iBAAA,EAAmB;AAC7C,QAAA,IAAI,cAAc,MAAM,YAAA;AACxB,QAAA,OAAO,GAAA;AAAA,MACT;AAEA,MAAA,IAAI,IAAA,CAAK,WAAW,OAAA,EAAS;AAC3B,QAAA,IAAI,cAAc,MAAM,YAAA;AACxB,QAAA,OAAO,GAAA;AAAA,MACT;AAEA,MAAA,IAAA,CAAK,OAAA,IAAW,CAAA;AAEhB,MAAA,MAAM,GAAA,GAAM,KAAK,GAAA,EAAI;AACrB,MAAA,IAAI,QAAQ,cAAA,CAAe,IAAA,CAAK,OAAA,EAAS,WAAA,EAAa,YAAY,MAAM,CAAA;AAExE,MAAA,IAAI,GAAA,EAAK;AACP,QAAA,MAAM,EAAA,GAAK,iBAAA,CAAkB,GAAA,CAAI,OAAA,EAAS,GAAG,CAAA;AAC7C,QAAA,IAAI,OAAO,EAAA,KAAO,QAAA,EAAU,KAAA,GAAQ,IAAA,CAAK,GAAA,CAAI,UAAA,EAAY,IAAA,CAAK,GAAA,CAAI,KAAA,EAAO,EAAE,CAAC,CAAA;AAAA,MAC9E;AAEA,MAAA,MAAM,IAAA,CAAK,OAAO,GAAG,CAAA;AAGrB,MAAA,GAAA,GAAM,MAAA,CAAO,MAAA,CAAO,EAAC,EAAG,GAAA,EAAK,EAAE,OAAA,EAAS,GAAA,CAAI,OAAA,GAAU,CAAA,EAAG,CAAA;AACzD,MAAC,GAAA,CAAY,QAAQ,CAAA,GAAI,IAAA;AAAA,IAC3B;AAAA,EACF,CAAA;AAEA,EAAA,OAAO;AAAA,IACL,IAAA,EAAM,OAAA;AAAA,IACN,KAAA,EAAO,CAAC,KAAA,KAAU;AAChB,MAAA,KAAA,CAAM,SAAS,CAAC,GAAI,MAAM,MAAA,IAAU,IAAK,KAAK,CAAA;AAAA,IAChD;AAAA,GACF;AACF","file":"index.cjs","sourcesContent":["import type { HttpPlugin } from \"@cedvict/http-guardian\";\nimport type { Guard } from \"@cedvict/http-guardian\";\nimport type { RequestContext } from \"@cedvict/http-guardian\";\n\nexport type RetryJitter = \"none\" | \"full\";\n\nexport type RetryPluginOptions = {\n retries?: number;\n baseDelayMs?: number;\n maxDelayMs?: number;\n jitter?: RetryJitter;\n retryOnStatuses?: number[];\n retryOnNetworkError?: boolean;\n /**\n * By default, retries only idempotent methods.\n */\n isRetryableRequest?: (ctx: RequestContext) => boolean;\n /**\n * Override wait logic (useful for tests).\n */\n wait?: (ms: number, ctx: RequestContext) => Promise<void>;\n};\n\nconst META_KEY = Symbol.for(\"http-guardian.retry\");\n\nfunction sleep(ms: number): Promise<void> {\n return new Promise((r) => setTimeout(r, ms));\n}\n\nfunction parseRetryAfterMs(h: Headers, nowMs: number): number | undefined {\n const v = h.get(\"retry-after\");\n if (!v) return undefined;\n const asInt = Number(v);\n if (Number.isFinite(asInt)) return Math.max(0, asInt * 1000);\n const asDate = Date.parse(v);\n if (!Number.isNaN(asDate)) return Math.max(0, asDate - nowMs);\n return undefined;\n}\n\nfunction isIdempotent(method: string): boolean {\n return method === \"GET\" || method === \"HEAD\" || method === \"OPTIONS\";\n}\n\nfunction backoffDelayMs(attempt: number, base: number, max: number, jitter: RetryJitter): number {\n // attempt starts at 1 for first retry\n const exp = Math.min(max, base * Math.pow(2, attempt - 1));\n if (jitter === \"full\") return Math.floor(Math.random() * exp);\n return exp;\n}\n\n/**\n * Production-grade retry plugin:\n * - exponential backoff (+ jitter)\n * - honors Retry-After for 429/503 etc\n * - idempotent only by default\n * - uses ctx.attempt to keep compatibility with other guards\n */\nexport function retryPlugin(options: RetryPluginOptions = {}): HttpPlugin {\n const retries = options.retries ?? 3;\n const baseDelayMs = options.baseDelayMs ?? 200;\n const maxDelayMs = options.maxDelayMs ?? 5_000;\n const jitter = options.jitter ?? \"full\";\n const retryOnStatuses = options.retryOnStatuses ?? [408, 429, 500, 502, 503, 504];\n const retryOnNetworkError = options.retryOnNetworkError ?? true;\n const isRetryableRequest = options.isRetryableRequest ?? ((ctx) => isIdempotent(ctx.method));\n const wait = options.wait ?? ((ms) => sleep(ms));\n\n const guard: Guard = async (ctx, next) => {\n if (!isRetryableRequest(ctx)) return next(ctx);\n\n const meta = ((ctx as any)[META_KEY] ??= { attempt: 0 }) as { attempt: number };\n // If another guard already replayed, do not loop forever:\n // retries count are independent from refresh, but we cap them.\n while (true) {\n let res: Response | undefined;\n let networkError: unknown | undefined;\n\n try {\n res = await next(ctx);\n } catch (e) {\n networkError = e;\n }\n\n const shouldRetryNetwork = !!networkError && retryOnNetworkError;\n const shouldRetryStatus = !!res && retryOnStatuses.includes(res.status);\n\n if (!shouldRetryNetwork && !shouldRetryStatus) {\n if (networkError) throw networkError;\n return res as Response;\n }\n\n if (meta.attempt >= retries) {\n if (networkError) throw networkError;\n return res as Response;\n }\n\n meta.attempt += 1;\n\n const now = Date.now();\n let delay = backoffDelayMs(meta.attempt, baseDelayMs, maxDelayMs, jitter);\n\n if (res) {\n const ra = parseRetryAfterMs(res.headers, now);\n if (typeof ra === \"number\") delay = Math.min(maxDelayMs, Math.max(delay, ra));\n }\n\n await wait(delay, ctx);\n\n // clone ctx with incremented attempt to keep anti-loop invariants aligned with core\n ctx = Object.assign({}, ctx, { attempt: ctx.attempt + 1 }) as RequestContext;\n (ctx as any)[META_KEY] = meta;\n }\n };\n\n return {\n name: \"retry\",\n apply: (draft) => {\n draft.guards = [...(draft.guards ?? []), guard];\n },\n };\n}\n"]}
|
package/dist/index.d.cts
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import { RequestContext, HttpPlugin } from '@cedvict/http-guardian';
|
|
2
|
+
|
|
3
|
+
type RetryJitter = "none" | "full";
|
|
4
|
+
type RetryPluginOptions = {
|
|
5
|
+
retries?: number;
|
|
6
|
+
baseDelayMs?: number;
|
|
7
|
+
maxDelayMs?: number;
|
|
8
|
+
jitter?: RetryJitter;
|
|
9
|
+
retryOnStatuses?: number[];
|
|
10
|
+
retryOnNetworkError?: boolean;
|
|
11
|
+
/**
|
|
12
|
+
* By default, retries only idempotent methods.
|
|
13
|
+
*/
|
|
14
|
+
isRetryableRequest?: (ctx: RequestContext) => boolean;
|
|
15
|
+
/**
|
|
16
|
+
* Override wait logic (useful for tests).
|
|
17
|
+
*/
|
|
18
|
+
wait?: (ms: number, ctx: RequestContext) => Promise<void>;
|
|
19
|
+
};
|
|
20
|
+
/**
|
|
21
|
+
* Production-grade retry plugin:
|
|
22
|
+
* - exponential backoff (+ jitter)
|
|
23
|
+
* - honors Retry-After for 429/503 etc
|
|
24
|
+
* - idempotent only by default
|
|
25
|
+
* - uses ctx.attempt to keep compatibility with other guards
|
|
26
|
+
*/
|
|
27
|
+
declare function retryPlugin(options?: RetryPluginOptions): HttpPlugin;
|
|
28
|
+
|
|
29
|
+
export { type RetryJitter, type RetryPluginOptions, retryPlugin };
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import { RequestContext, HttpPlugin } from '@cedvict/http-guardian';
|
|
2
|
+
|
|
3
|
+
type RetryJitter = "none" | "full";
|
|
4
|
+
type RetryPluginOptions = {
|
|
5
|
+
retries?: number;
|
|
6
|
+
baseDelayMs?: number;
|
|
7
|
+
maxDelayMs?: number;
|
|
8
|
+
jitter?: RetryJitter;
|
|
9
|
+
retryOnStatuses?: number[];
|
|
10
|
+
retryOnNetworkError?: boolean;
|
|
11
|
+
/**
|
|
12
|
+
* By default, retries only idempotent methods.
|
|
13
|
+
*/
|
|
14
|
+
isRetryableRequest?: (ctx: RequestContext) => boolean;
|
|
15
|
+
/**
|
|
16
|
+
* Override wait logic (useful for tests).
|
|
17
|
+
*/
|
|
18
|
+
wait?: (ms: number, ctx: RequestContext) => Promise<void>;
|
|
19
|
+
};
|
|
20
|
+
/**
|
|
21
|
+
* Production-grade retry plugin:
|
|
22
|
+
* - exponential backoff (+ jitter)
|
|
23
|
+
* - honors Retry-After for 429/503 etc
|
|
24
|
+
* - idempotent only by default
|
|
25
|
+
* - uses ctx.attempt to keep compatibility with other guards
|
|
26
|
+
*/
|
|
27
|
+
declare function retryPlugin(options?: RetryPluginOptions): HttpPlugin;
|
|
28
|
+
|
|
29
|
+
export { type RetryJitter, type RetryPluginOptions, retryPlugin };
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
// src/index.ts
|
|
2
|
+
var META_KEY = /* @__PURE__ */ Symbol.for("http-guardian.retry");
|
|
3
|
+
function sleep(ms) {
|
|
4
|
+
return new Promise((r) => setTimeout(r, ms));
|
|
5
|
+
}
|
|
6
|
+
function parseRetryAfterMs(h, nowMs) {
|
|
7
|
+
const v = h.get("retry-after");
|
|
8
|
+
if (!v) return void 0;
|
|
9
|
+
const asInt = Number(v);
|
|
10
|
+
if (Number.isFinite(asInt)) return Math.max(0, asInt * 1e3);
|
|
11
|
+
const asDate = Date.parse(v);
|
|
12
|
+
if (!Number.isNaN(asDate)) return Math.max(0, asDate - nowMs);
|
|
13
|
+
return void 0;
|
|
14
|
+
}
|
|
15
|
+
function isIdempotent(method) {
|
|
16
|
+
return method === "GET" || method === "HEAD" || method === "OPTIONS";
|
|
17
|
+
}
|
|
18
|
+
function backoffDelayMs(attempt, base, max, jitter) {
|
|
19
|
+
const exp = Math.min(max, base * Math.pow(2, attempt - 1));
|
|
20
|
+
if (jitter === "full") return Math.floor(Math.random() * exp);
|
|
21
|
+
return exp;
|
|
22
|
+
}
|
|
23
|
+
function retryPlugin(options = {}) {
|
|
24
|
+
const retries = options.retries ?? 3;
|
|
25
|
+
const baseDelayMs = options.baseDelayMs ?? 200;
|
|
26
|
+
const maxDelayMs = options.maxDelayMs ?? 5e3;
|
|
27
|
+
const jitter = options.jitter ?? "full";
|
|
28
|
+
const retryOnStatuses = options.retryOnStatuses ?? [408, 429, 500, 502, 503, 504];
|
|
29
|
+
const retryOnNetworkError = options.retryOnNetworkError ?? true;
|
|
30
|
+
const isRetryableRequest = options.isRetryableRequest ?? ((ctx) => isIdempotent(ctx.method));
|
|
31
|
+
const wait = options.wait ?? ((ms) => sleep(ms));
|
|
32
|
+
const guard = async (ctx, next) => {
|
|
33
|
+
if (!isRetryableRequest(ctx)) return next(ctx);
|
|
34
|
+
const meta = ctx[META_KEY] ??= { attempt: 0 };
|
|
35
|
+
while (true) {
|
|
36
|
+
let res;
|
|
37
|
+
let networkError;
|
|
38
|
+
try {
|
|
39
|
+
res = await next(ctx);
|
|
40
|
+
} catch (e) {
|
|
41
|
+
networkError = e;
|
|
42
|
+
}
|
|
43
|
+
const shouldRetryNetwork = !!networkError && retryOnNetworkError;
|
|
44
|
+
const shouldRetryStatus = !!res && retryOnStatuses.includes(res.status);
|
|
45
|
+
if (!shouldRetryNetwork && !shouldRetryStatus) {
|
|
46
|
+
if (networkError) throw networkError;
|
|
47
|
+
return res;
|
|
48
|
+
}
|
|
49
|
+
if (meta.attempt >= retries) {
|
|
50
|
+
if (networkError) throw networkError;
|
|
51
|
+
return res;
|
|
52
|
+
}
|
|
53
|
+
meta.attempt += 1;
|
|
54
|
+
const now = Date.now();
|
|
55
|
+
let delay = backoffDelayMs(meta.attempt, baseDelayMs, maxDelayMs, jitter);
|
|
56
|
+
if (res) {
|
|
57
|
+
const ra = parseRetryAfterMs(res.headers, now);
|
|
58
|
+
if (typeof ra === "number") delay = Math.min(maxDelayMs, Math.max(delay, ra));
|
|
59
|
+
}
|
|
60
|
+
await wait(delay, ctx);
|
|
61
|
+
ctx = Object.assign({}, ctx, { attempt: ctx.attempt + 1 });
|
|
62
|
+
ctx[META_KEY] = meta;
|
|
63
|
+
}
|
|
64
|
+
};
|
|
65
|
+
return {
|
|
66
|
+
name: "retry",
|
|
67
|
+
apply: (draft) => {
|
|
68
|
+
draft.guards = [...draft.guards ?? [], guard];
|
|
69
|
+
}
|
|
70
|
+
};
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
export { retryPlugin };
|
|
74
|
+
//# sourceMappingURL=index.js.map
|
|
75
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/index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type { Guard } from \"@cedvict/http-guardian\";\nimport type { RequestContext } from \"@cedvict/http-guardian\";\n\nexport type RetryJitter = \"none\" | \"full\";\n\nexport type RetryPluginOptions = {\n retries?: number;\n baseDelayMs?: number;\n maxDelayMs?: number;\n jitter?: RetryJitter;\n retryOnStatuses?: number[];\n retryOnNetworkError?: boolean;\n /**\n * By default, retries only idempotent methods.\n */\n isRetryableRequest?: (ctx: RequestContext) => boolean;\n /**\n * Override wait logic (useful for tests).\n */\n wait?: (ms: number, ctx: RequestContext) => Promise<void>;\n};\n\nconst META_KEY = Symbol.for(\"http-guardian.retry\");\n\nfunction sleep(ms: number): Promise<void> {\n return new Promise((r) => setTimeout(r, ms));\n}\n\nfunction parseRetryAfterMs(h: Headers, nowMs: number): number | undefined {\n const v = h.get(\"retry-after\");\n if (!v) return undefined;\n const asInt = Number(v);\n if (Number.isFinite(asInt)) return Math.max(0, asInt * 1000);\n const asDate = Date.parse(v);\n if (!Number.isNaN(asDate)) return Math.max(0, asDate - nowMs);\n return undefined;\n}\n\nfunction isIdempotent(method: string): boolean {\n return method === \"GET\" || method === \"HEAD\" || method === \"OPTIONS\";\n}\n\nfunction backoffDelayMs(attempt: number, base: number, max: number, jitter: RetryJitter): number {\n // attempt starts at 1 for first retry\n const exp = Math.min(max, base * Math.pow(2, attempt - 1));\n if (jitter === \"full\") return Math.floor(Math.random() * exp);\n return exp;\n}\n\n/**\n * Production-grade retry plugin:\n * - exponential backoff (+ jitter)\n * - honors Retry-After for 429/503 etc\n * - idempotent only by default\n * - uses ctx.attempt to keep compatibility with other guards\n */\nexport function retryPlugin(options: RetryPluginOptions = {}): HttpPlugin {\n const retries = options.retries ?? 3;\n const baseDelayMs = options.baseDelayMs ?? 200;\n const maxDelayMs = options.maxDelayMs ?? 5_000;\n const jitter = options.jitter ?? \"full\";\n const retryOnStatuses = options.retryOnStatuses ?? [408, 429, 500, 502, 503, 504];\n const retryOnNetworkError = options.retryOnNetworkError ?? true;\n const isRetryableRequest = options.isRetryableRequest ?? ((ctx) => isIdempotent(ctx.method));\n const wait = options.wait ?? ((ms) => sleep(ms));\n\n const guard: Guard = async (ctx, next) => {\n if (!isRetryableRequest(ctx)) return next(ctx);\n\n const meta = ((ctx as any)[META_KEY] ??= { attempt: 0 }) as { attempt: number };\n // If another guard already replayed, do not loop forever:\n // retries count are independent from refresh, but we cap them.\n while (true) {\n let res: Response | undefined;\n let networkError: unknown | undefined;\n\n try {\n res = await next(ctx);\n } catch (e) {\n networkError = e;\n }\n\n const shouldRetryNetwork = !!networkError && retryOnNetworkError;\n const shouldRetryStatus = !!res && retryOnStatuses.includes(res.status);\n\n if (!shouldRetryNetwork && !shouldRetryStatus) {\n if (networkError) throw networkError;\n return res as Response;\n }\n\n if (meta.attempt >= retries) {\n if (networkError) throw networkError;\n return res as Response;\n }\n\n meta.attempt += 1;\n\n const now = Date.now();\n let delay = backoffDelayMs(meta.attempt, baseDelayMs, maxDelayMs, jitter);\n\n if (res) {\n const ra = parseRetryAfterMs(res.headers, now);\n if (typeof ra === \"number\") delay = Math.min(maxDelayMs, Math.max(delay, ra));\n }\n\n await wait(delay, ctx);\n\n // clone ctx with incremented attempt to keep anti-loop invariants aligned with core\n ctx = Object.assign({}, ctx, { attempt: ctx.attempt + 1 }) as RequestContext;\n (ctx as any)[META_KEY] = meta;\n }\n };\n\n return {\n name: \"retry\",\n apply: (draft) => {\n draft.guards = [...(draft.guards ?? []), guard];\n },\n };\n}\n"]}
|
package/package.json
ADDED
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@cedvict/http-guardian-plugin-retry",
|
|
3
|
+
"version": "0.0.1-next.10",
|
|
4
|
+
"description": "Retry plugin (exponential backoff) for http-guardian.",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"exports": {
|
|
7
|
+
".": {
|
|
8
|
+
"types": "./dist/index.d.ts",
|
|
9
|
+
"browser": "./dist/index.js",
|
|
10
|
+
"import": "./dist/index.js",
|
|
11
|
+
"require": "./dist/index.cjs",
|
|
12
|
+
"default": "./dist/index.js"
|
|
13
|
+
}
|
|
14
|
+
},
|
|
15
|
+
"main": "./dist/index.cjs",
|
|
16
|
+
"module": "./dist/index.js",
|
|
17
|
+
"types": "./dist/index.d.ts",
|
|
18
|
+
"files": [
|
|
19
|
+
"dist",
|
|
20
|
+
"README.md",
|
|
21
|
+
"LICENSE",
|
|
22
|
+
"CHANGELOG.md"
|
|
23
|
+
],
|
|
24
|
+
"sideEffects": false,
|
|
25
|
+
"engines": {
|
|
26
|
+
"node": ">=22"
|
|
27
|
+
},
|
|
28
|
+
"license": "MIT",
|
|
29
|
+
"repository": {
|
|
30
|
+
"type": "git",
|
|
31
|
+
"url": "git+https://github.com/cedvict/http-guardian.git"
|
|
32
|
+
},
|
|
33
|
+
"peerDependencies": {
|
|
34
|
+
"@cedvict/http-guardian": "^0.0.1-next.6"
|
|
35
|
+
},
|
|
36
|
+
"scripts": {
|
|
37
|
+
"build": "tsup",
|
|
38
|
+
"dev": "tsup --watch",
|
|
39
|
+
"test": "vitest run",
|
|
40
|
+
"lint": "eslint . --max-warnings=0",
|
|
41
|
+
"typecheck": "tsc -p tsconfig.typecheck.json --noEmit",
|
|
42
|
+
"prepublishOnly": "npm -w @cedvict/http-guardian run build && npm run test && npm run lint && npm run typecheck && npm run build",
|
|
43
|
+
"prebuild": "npm -w @cedvict/http-guardian run build",
|
|
44
|
+
"pretypecheck": "npm -w @cedvict/http-guardian run build"
|
|
45
|
+
},
|
|
46
|
+
"devDependencies": {
|
|
47
|
+
"@types/node": "^20.0.0",
|
|
48
|
+
"eslint": "^9.0.0",
|
|
49
|
+
"typescript": "^5.4.0",
|
|
50
|
+
"tsup": "^8.0.0",
|
|
51
|
+
"vitest": "^1.5.0",
|
|
52
|
+
"@typescript-eslint/parser": "^8.0.0",
|
|
53
|
+
"@typescript-eslint/eslint-plugin": "^8.0.0"
|
|
54
|
+
},
|
|
55
|
+
"dependencies": {
|
|
56
|
+
"@cedvict/http-guardian": "^0.0.1-next.10"
|
|
57
|
+
}
|
|
58
|
+
}
|