11cb0ef41Sopenharmony_ci'use strict';
21cb0ef41Sopenharmony_ci
31cb0ef41Sopenharmony_ciconst common = require('../common');
41cb0ef41Sopenharmony_ciconst assert = require('assert');
51cb0ef41Sopenharmony_ciconst http = require('http');
61cb0ef41Sopenharmony_ciconst Agent = http.Agent;
71cb0ef41Sopenharmony_ci
81cb0ef41Sopenharmony_ciconst server = http.createServer(common.mustCall((req, res) => {
91cb0ef41Sopenharmony_ci  res.end('hello world');
101cb0ef41Sopenharmony_ci}, 2));
111cb0ef41Sopenharmony_ci
121cb0ef41Sopenharmony_ciserver.listen(0, () => {
131cb0ef41Sopenharmony_ci  const agent = new Agent({ keepAlive: true });
141cb0ef41Sopenharmony_ci
151cb0ef41Sopenharmony_ci  const requestParams = {
161cb0ef41Sopenharmony_ci    host: 'localhost',
171cb0ef41Sopenharmony_ci    port: server.address().port,
181cb0ef41Sopenharmony_ci    agent: agent,
191cb0ef41Sopenharmony_ci    path: '/'
201cb0ef41Sopenharmony_ci  };
211cb0ef41Sopenharmony_ci
221cb0ef41Sopenharmony_ci  const socketKey = agent.getName(requestParams);
231cb0ef41Sopenharmony_ci
241cb0ef41Sopenharmony_ci  http.get(requestParams, common.mustCall((res) => {
251cb0ef41Sopenharmony_ci    assert.strictEqual(res.statusCode, 200);
261cb0ef41Sopenharmony_ci    res.resume();
271cb0ef41Sopenharmony_ci    res.on('end', common.mustCall(() => {
281cb0ef41Sopenharmony_ci      process.nextTick(common.mustCall(() => {
291cb0ef41Sopenharmony_ci        const freeSockets = agent.freeSockets[socketKey];
301cb0ef41Sopenharmony_ci        // Expect a free socket on socketKey
311cb0ef41Sopenharmony_ci        assert.strictEqual(freeSockets.length, 1);
321cb0ef41Sopenharmony_ci
331cb0ef41Sopenharmony_ci        // Generate a random error on the free socket
341cb0ef41Sopenharmony_ci        const freeSocket = freeSockets[0];
351cb0ef41Sopenharmony_ci        freeSocket.emit('error', new Error('ECONNRESET: test'));
361cb0ef41Sopenharmony_ci
371cb0ef41Sopenharmony_ci        http.get(requestParams, done);
381cb0ef41Sopenharmony_ci      }));
391cb0ef41Sopenharmony_ci    }));
401cb0ef41Sopenharmony_ci  }));
411cb0ef41Sopenharmony_ci
421cb0ef41Sopenharmony_ci  function done() {
431cb0ef41Sopenharmony_ci    // Expect the freeSockets pool to be empty
441cb0ef41Sopenharmony_ci    assert.strictEqual(Object.keys(agent.freeSockets).length, 0);
451cb0ef41Sopenharmony_ci
461cb0ef41Sopenharmony_ci    agent.destroy();
471cb0ef41Sopenharmony_ci    server.close();
481cb0ef41Sopenharmony_ci  }
491cb0ef41Sopenharmony_ci});
50