• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1'use strict';
2
3const common = require('../common');
4const assert = require('assert');
5const { createServer } = require('http');
6const { connect } = require('net');
7
8// This test validates that the server returns 408
9// after server.requestTimeout if the client
10// does not complete a request, and that keep alive
11// works properly
12
13function performRequestWithDelay(client, firstDelay, secondDelay) {
14  client.resume();
15  client.write('GET / HTTP/1.1\r\n');
16
17  firstDelay = common.platformTimeout(firstDelay);
18  secondDelay = common.platformTimeout(secondDelay);
19
20  console.log('performRequestWithDelay', firstDelay, secondDelay);
21
22  setTimeout(() => {
23    client.write('Connection: ');
24  }, firstDelay).unref();
25
26  // Complete the request
27  setTimeout(() => {
28    client.write('keep-alive\r\n\r\n');
29  }, firstDelay + secondDelay).unref();
30}
31
32const server = createServer(common.mustCallAtLeast((req, res) => {
33  res.writeHead(200, { 'Content-Type': 'text/plain' });
34  res.end();
35}));
36
37// 0 seconds is the default
38assert.strictEqual(server.requestTimeout, 0);
39const requestTimeout = common.platformTimeout(1000);
40server.requestTimeout = requestTimeout;
41assert.strictEqual(server.requestTimeout, requestTimeout);
42
43// Make sure keepAliveTimeout is big enough for the requestTimeout.
44server.keepAliveTimeout = 0;
45
46server.listen(0, common.mustCall(() => {
47  const client = connect(server.address().port);
48  let second = false;
49  let response = '';
50
51  client.on('data', common.mustCallAtLeast((chunk) => {
52    response += chunk.toString('utf-8');
53
54    // First response has ended
55    if (!second && response.endsWith('\r\n\r\n')) {
56      assert.strictEqual(
57        response.split('\r\n')[0],
58        'HTTP/1.1 200 OK'
59      );
60
61      const defer = common.platformTimeout(server.requestTimeout * 1.5);
62
63      console.log('defer by', defer);
64
65      // Wait some time to make sure requestTimeout
66      // does not interfere with keep alive
67      setTimeout(() => {
68        response = '';
69        second = true;
70
71        // Perform a second request expected to finish after requestTimeout
72        performRequestWithDelay(client, 1000, 3000);
73      }, defer).unref();
74    }
75  }, 1));
76
77  const errOrEnd = common.mustCall(function(err) {
78    console.log(err);
79    assert.strictEqual(second, true);
80    assert.strictEqual(
81      response,
82      // Empty because of https://github.com/nodejs/node/commit/e8d7fedf7cad6e612e4f2e0456e359af57608ac7
83      // 'HTTP/1.1 408 Request Timeout\r\nConnection: close\r\n\r\n'
84      ''
85    );
86    server.close();
87  });
88
89  client.on('error', errOrEnd);
90  client.on('end', errOrEnd);
91
92  // Perform a second request expected to finish before requestTimeout
93  performRequestWithDelay(client, 50, 500);
94}));
95