From 87e779160e491ce1b41ab3c873fcecec71cda32b Mon Sep 17 00:00:00 2001 From: Mathias Buus Date: Wed, 8 Sep 2021 17:45:21 +0200 Subject: [PATCH] option to disable retries --- index.js | 1 + lib/io.js | 3 ++- test.js | 32 ++++++++++++++++++++++++++++++++ 3 files changed, 35 insertions(+), 1 deletion(-) diff --git a/index.js b/index.js index 8cf7ca8..88924f4 100644 --- a/index.js +++ b/index.js @@ -128,6 +128,7 @@ class DHT extends EventEmitter { const req = this.io.createRequest({ id: null, host, port }, token, command, target, value) if (opts && opts.socket) req.socket = opts.socket + if (opts && opts.retry === false) req.retries = 0 return new Promise((resolve, reject) => { req.onresponse = resolve diff --git a/lib/io.js b/lib/io.js index b5d93ce..369e202 100644 --- a/lib/io.js +++ b/lib/io.js @@ -204,6 +204,7 @@ class Request { this.target = target this.value = value this.sent = 0 + this.retries = 3 this.destroyed = false this.oncycle = noop @@ -388,7 +389,7 @@ function noop () {} function oncycle (req) { req._timeout = null req.oncycle(req) - if (req.sent === 3) { + if (req.sent >= req.retries) { req.destroy(TIMEOUT) req._io.ontimeout(req) } else { diff --git a/test.js b/test.js index c1a18f7..462cb87 100644 --- a/test.js +++ b/test.js @@ -125,6 +125,38 @@ tape('timeouts', async function (t) { b.destroy() }) +tape('request with/without retries', async function (t) { + const [bootstrap, a, b] = await makeSwarm(3) + let tries = 0 + + b.on('request', function (req) { + if (req.command === 'nope') { + tries++ + t.pass('ignoring request') + } + }) + + try { + await a.request({ command: 'nope', target: Buffer.alloc(32) }, { host: '127.0.0.1', port: b.address().port }) + } catch { + // do nothing + } + + t.same(tries, 3) + + try { + await a.request({ command: 'nope', target: Buffer.alloc(32) }, { host: '127.0.0.1', port: b.address().port }, { retry: false }) + } catch { + // do nothing + } + + t.same(tries, 4) + + bootstrap.destroy() + a.destroy() + b.destroy() +}) + tape('shorthand commit', async function (t) { const swarm = await makeSwarm(40)