summaryrefslogtreecommitdiff
path: root/test/parallel/test-http-server-consumed-timeout.js
blob: 865169ca0103759db2d159f496c59d131ef71c72 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
'use strict';

const common = require('../common');

const assert = require('assert');
const http = require('http');

const durationBetweenIntervals = [];
let timeoutTooShort = false;
const TIMEOUT = common.platformTimeout(200);
const INTERVAL = Math.floor(TIMEOUT / 8);

runTest(TIMEOUT);

function runTest(timeoutDuration) {
  let intervalWasInvoked = false;
  let newTimeoutDuration = 0;
  const closeCallback = (err) => {
    assert.ifError(err);
    if (newTimeoutDuration) {
      runTest(newTimeoutDuration);
    }
  };

  const server = http.createServer((req, res) => {
    server.close(common.mustCall(closeCallback));

    res.writeHead(200);
    res.flushHeaders();

    req.setTimeout(timeoutDuration, () => {
      if (!intervalWasInvoked) {
        // Interval wasn't invoked, probably because the machine is busy with
        // other things. Try again with a longer timeout.
        newTimeoutDuration = timeoutDuration * 2;
        console.error('The interval was not invoked.');
        console.error(`Trying w/ timeout of ${newTimeoutDuration}.`);
        return;
      }

      if (timeoutTooShort) {
        intervalWasInvoked = false;
        timeoutTooShort = false;
        newTimeoutDuration =
          Math.max(...durationBetweenIntervals, timeoutDuration) * 2;
        console.error(`Time between intervals: ${durationBetweenIntervals}`);
        console.error(`Trying w/ timeout of ${newTimeoutDuration}`);
        return;
      }

      assert.fail('Request timeout should not fire');
    });

    req.resume();
    req.once('end', () => {
      res.end();
    });
  });

  server.listen(0, common.mustCall(() => {
    const req = http.request({
      port: server.address().port,
      method: 'POST'
    }, () => {
      let lastIntervalTimestamp = Date.now();
      const interval = setInterval(() => {
        const lastDuration = Date.now() - lastIntervalTimestamp;
        durationBetweenIntervals.push(lastDuration);
        lastIntervalTimestamp = Date.now();
        if (lastDuration > timeoutDuration / 2) {
          // The interval is supposed to be about 1/8 of the timeout duration.
          // If it's running so infrequently that it's greater than 1/2 the
          // timeout duration, then run the test again with a longer timeout.
          timeoutTooShort = true;
        }
        intervalWasInvoked = true;
        req.write('a');
      }, INTERVAL);
      setTimeout(() => {
        clearInterval(interval);
        req.end();
      }, timeoutDuration);
    });
    req.write('.');
  }));
}