11cb0ef41Sopenharmony_ci'use strict'; 21cb0ef41Sopenharmony_ci// Flags: --expose-gc 31cb0ef41Sopenharmony_ci 41cb0ef41Sopenharmony_ci// Tests that memoryUsage().external doesn't go negative 51cb0ef41Sopenharmony_ci// when a lot tls connections are opened and closed 61cb0ef41Sopenharmony_ci 71cb0ef41Sopenharmony_ciconst common = require('../common'); 81cb0ef41Sopenharmony_ciif (!common.hasCrypto) 91cb0ef41Sopenharmony_ci common.skip('missing crypto'); 101cb0ef41Sopenharmony_ci 111cb0ef41Sopenharmony_ciconst makeDuplexPair = require('../common/duplexpair'); 121cb0ef41Sopenharmony_ciconst onGC = require('../common/ongc'); 131cb0ef41Sopenharmony_ciconst assert = require('assert'); 141cb0ef41Sopenharmony_ciconst tls = require('tls'); 151cb0ef41Sopenharmony_ci 161cb0ef41Sopenharmony_ci// Payload doesn't matter. We just need to have the tls 171cb0ef41Sopenharmony_ci// connection try and connect somewhere. 181cb0ef41Sopenharmony_ciconst dummyPayload = Buffer.alloc(10000, 'yolo'); 191cb0ef41Sopenharmony_ci 201cb0ef41Sopenharmony_cilet runs = 0; 211cb0ef41Sopenharmony_ci 221cb0ef41Sopenharmony_ci// Count garbage-collected TLS sockets. 231cb0ef41Sopenharmony_cilet gced = 0; 241cb0ef41Sopenharmony_cifunction ongc() { gced++; } 251cb0ef41Sopenharmony_ci 261cb0ef41Sopenharmony_ciconnect(); 271cb0ef41Sopenharmony_ci 281cb0ef41Sopenharmony_cifunction connect() { 291cb0ef41Sopenharmony_ci if (runs % 64 === 0) 301cb0ef41Sopenharmony_ci global.gc(); 311cb0ef41Sopenharmony_ci const externalMemoryUsage = process.memoryUsage().external; 321cb0ef41Sopenharmony_ci assert(externalMemoryUsage >= 0, `${externalMemoryUsage} < 0`); 331cb0ef41Sopenharmony_ci if (runs++ === 512) { 341cb0ef41Sopenharmony_ci // Make sure at least half the TLS sockets have been garbage collected 351cb0ef41Sopenharmony_ci // (so that this test can actually check what it's testing): 361cb0ef41Sopenharmony_ci assert(gced >= 256, `${gced} < 256`); 371cb0ef41Sopenharmony_ci return; 381cb0ef41Sopenharmony_ci } 391cb0ef41Sopenharmony_ci 401cb0ef41Sopenharmony_ci const { clientSide, serverSide } = makeDuplexPair(); 411cb0ef41Sopenharmony_ci 421cb0ef41Sopenharmony_ci const tlsSocket = tls.connect({ socket: clientSide }); 431cb0ef41Sopenharmony_ci tlsSocket.on('error', common.mustCall(connect)); 441cb0ef41Sopenharmony_ci onGC(tlsSocket, { ongc }); 451cb0ef41Sopenharmony_ci 461cb0ef41Sopenharmony_ci // Use setImmediate so that we don't trigger the error within the same 471cb0ef41Sopenharmony_ci // event loop tick. 481cb0ef41Sopenharmony_ci setImmediate(() => serverSide.write(dummyPayload)); 491cb0ef41Sopenharmony_ci} 50