From 1b1f310167383b48339fd730609b5ec859e79f1a Mon Sep 17 00:00:00 2001 From: Leonardo Rossi Date: Thu, 30 Sep 2021 15:31:28 +0200 Subject: [PATCH] adds maxRetriesOn503 option --- README.md | 11 +++++++++++ index.js | 8 ++++---- 2 files changed, 15 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index 83c48f46..077f4466 100644 --- a/README.md +++ b/README.md @@ -198,6 +198,17 @@ By default: `['GET', 'HEAD', 'OPTIONS', 'TRACE' ]` This plugin will always retry on 503 errors, _unless_ `retryMethods` does not contain `GET`. +--- + +#### `maxRetriesOn503` + +This plugin will always retry on `GET` requests that returns 503 errors, _unless_ `retryMethods` does not contain `GET`. + +This option set the limit on how many times the plugin should retry the request, specifically for 503 errors. + +By Default: 10 + + --- ### `reply.from(source, [opts])` diff --git a/index.js b/index.js index 53eb55f7..5362311a 100644 --- a/index.js +++ b/index.js @@ -43,6 +43,7 @@ module.exports = fp(function from (fastify, opts, next) { const getUpstream = opts.getUpstream || upstreamNoOp const onError = opts.onError || onErrorDefault const retriesCount = opts.retriesCount || 0 + const maxRetriesOn503 = opts.maxRetriesOn503 || 10 if (!source) { source = req.url @@ -119,7 +120,7 @@ module.exports = fp(function from (fastify, opts, next) { const contentLength = requestHeaders['content-length'] let requestImpl if (retryMethods.has(req.method) && !contentLength) { - requestImpl = createRequestRetry(request, this, retriesCount, retryOnError) + requestImpl = createRequestRetry(request, this, retriesCount, retryOnError, maxRetriesOn503) } else { requestImpl = request } @@ -212,9 +213,8 @@ function isFastifyMultipartRegistered (fastify) { return fastify.hasContentTypeParser('multipart') && fastify.hasRequestDecorator('multipart') } -function createRequestRetry (requestImpl, reply, retriesCount, retryOnError) { +function createRequestRetry (requestImpl, reply, retriesCount, retryOnError, maxRetriesOn503) { function requestRetry (req, cb) { - const MAX_RETRIES_ON_503 = 10 let retries = 0 function run () { @@ -228,7 +228,7 @@ function createRequestRetry (requestImpl, reply, retriesCount, retryOnError) { if (!reply.sent) { // always retry on 503 errors if (res && res.statusCode === 503 && req.method === 'GET') { - if (retriesCount === 0 && retries < MAX_RETRIES_ON_503) { + if (retriesCount === 0 && retries < maxRetriesOn503) { // we should stop at some point return retry(retryAfter) }