|
| 1 | +'use strict'; |
| 2 | +const common = require('../common'); |
| 3 | +const dnstools = require('../common/dns'); |
| 4 | +const dns = require('dns'); |
| 5 | +const assert = require('assert'); |
| 6 | +const dgram = require('dgram'); |
| 7 | + |
| 8 | +const server = dgram.createSocket('udp4'); |
| 9 | +const nxdomain = 'nxdomain.org'; |
| 10 | +const domain = 'example.org'; |
| 11 | +const answers = [{ type: 'A', address: '1.2.3.4', ttl: 123, domain }]; |
| 12 | + |
| 13 | +server.on('message', common.mustCallAtLeast((msg, { address, port }) => { |
| 14 | + const parsed = dnstools.parseDNSPacket(msg); |
| 15 | + if (parsed.questions[0].domain === nxdomain) { |
| 16 | + return; |
| 17 | + } |
| 18 | + assert.strictEqual(parsed.questions[0].domain, domain); |
| 19 | + server.send(dnstools.writeDNSPacket({ |
| 20 | + id: parsed.id, |
| 21 | + questions: parsed.questions, |
| 22 | + answers: answers, |
| 23 | + }), port, address); |
| 24 | +}), 1); |
| 25 | + |
| 26 | +server.bind(0, common.mustCall(async () => { |
| 27 | + const address = server.address(); |
| 28 | + // Test if the Resolver works as before. |
| 29 | + const resolver = new dns.promises.Resolver({ timeout: 1000, tries: 1, maxTimeouts: 1000 }); |
| 30 | + resolver.setServers([`127.0.0.1:${address.port}`]); |
| 31 | + const res = await resolver.resolveAny('example.org'); |
| 32 | + assert.strictEqual(res.length, 1); |
| 33 | + assert.strictEqual(res.length, answers.length); |
| 34 | + assert.strictEqual(res[0].address, answers[0].address); |
| 35 | + |
| 36 | + // Test that maxTimeout is effective. |
| 37 | + // Without maxTimeout, the timeout will keep increasing when retrying. |
| 38 | + const timeout1 = await timeout(address, { timeout: 500, tries: 3 }); |
| 39 | + // With maxTimeout, the timeout will always 500 when retrying. |
| 40 | + const timeout2 = await timeout(address, { timeout: 500, tries: 3, maxTimeout: 500 }); |
| 41 | + console.log(`timeout1: ${timeout1}, timeout2: ${timeout2}`); |
| 42 | + assert.strictEqual(timeout1 !== undefined && timeout2 !== undefined, true); |
| 43 | + assert.strictEqual(timeout1 > timeout2, true); |
| 44 | + server.close(); |
| 45 | +})); |
| 46 | + |
| 47 | +async function timeout(address, options) { |
| 48 | + const start = Date.now(); |
| 49 | + const resolver = new dns.promises.Resolver(options); |
| 50 | + resolver.setServers([`127.0.0.1:${address.port}`]); |
| 51 | + try { |
| 52 | + await resolver.resolveAny(nxdomain); |
| 53 | + } catch (e) { |
| 54 | + assert.strictEqual(e.code, 'ETIMEOUT'); |
| 55 | + return Date.now() - start; |
| 56 | + } |
| 57 | +} |
0 commit comments