1'use strict';
2const common = require('../common.js');
3const bench = common.createBenchmark(main, {
4  dur: [5],
5  type: ['buf', 'asc', 'utf'],
6  size: [100, 1024, 1024 * 1024, 4 * 1024 * 1024, 16 * 1024 * 1024],
7});
8
9const fixtures = require('../../test/common/fixtures');
10let options;
11const tls = require('tls');
12
13function main({ dur, type, size }) {
14  let encoding;
15  let chunk;
16  switch (type) {
17    case 'buf':
18      chunk = Buffer.alloc(size, 'b');
19      break;
20    case 'asc':
21      chunk = 'a'.repeat(size);
22      encoding = 'ascii';
23      break;
24    case 'utf':
25      chunk = 'ü'.repeat(size / 2);
26      encoding = 'utf8';
27      break;
28    default:
29      throw new Error('invalid type');
30  }
31
32  options = {
33    key: fixtures.readKey('rsa_private.pem'),
34    cert: fixtures.readKey('rsa_cert.crt'),
35    ca: fixtures.readKey('rsa_ca.crt'),
36    ciphers: 'AES256-GCM-SHA384',
37    maxVersion: 'TLSv1.2',
38  };
39
40  const server = tls.createServer(options, onConnection);
41  let conn;
42  server.listen(common.PORT, () => {
43    const opt = { port: common.PORT, rejectUnauthorized: false };
44    conn = tls.connect(opt, () => {
45      setTimeout(done, dur * 1000);
46      bench.start();
47      conn.on('drain', write);
48      write();
49    });
50
51    function write() {
52      while (false !== conn.write(chunk, encoding));
53    }
54  });
55
56  let received = 0;
57  function onConnection(conn) {
58    conn.on('data', (chunk) => {
59      received += chunk.length;
60    });
61  }
62
63  function done() {
64    const mbits = (received * 8) / (1024 * 1024);
65    bench.end(mbits);
66    if (conn)
67      conn.destroy();
68    server.close();
69  }
70}
71