1'use strict'; 2 3const common = require('../common'); 4const assert = require('assert'); 5const initHooks = require('./init-hooks'); 6const { checkInvocations } = require('./hook-checks'); 7const net = require('net'); 8 9const hooks = initHooks(); 10hooks.enable(); 11 12// 13// Creating server and listening on port 14// 15const server = net.createServer() 16 .on('listening', common.mustCall(onlistening)) 17 .on('connection', common.mustCall(onconnection)) 18 .listen(0); 19 20assert.strictEqual(hooks.activitiesOfTypes('WRITEWRAP').length, 0); 21 22function onlistening() { 23 assert.strictEqual(hooks.activitiesOfTypes('WRITEWRAP').length, 0); 24 // 25 // Creating client and connecting it to server 26 // 27 net 28 .connect(server.address().port) 29 .on('connect', common.mustCall(onconnect)); 30 31 assert.strictEqual(hooks.activitiesOfTypes('WRITEWRAP').length, 0); 32} 33 34function checkDestroyedWriteWraps(n, stage) { 35 const as = hooks.activitiesOfTypes('WRITEWRAP'); 36 assert.strictEqual(as.length, n, 37 `${as.length} out of ${n} WRITEWRAPs when ${stage}`); 38 39 function checkValidWriteWrap(w) { 40 assert.strictEqual(w.type, 'WRITEWRAP'); 41 assert.strictEqual(typeof w.uid, 'number'); 42 assert.strictEqual(typeof w.triggerAsyncId, 'number'); 43 44 checkInvocations(w, { init: 1 }, `when ${stage}`); 45 } 46 as.forEach(checkValidWriteWrap); 47} 48 49function onconnection(conn) { 50 conn.write('hi'); // Let the client know we're ready. 51 conn.resume(); 52 // 53 // Server received client connection 54 // 55 checkDestroyedWriteWraps(0, 'server got connection'); 56} 57 58function onconnect() { 59 // 60 // Client connected to server 61 // 62 checkDestroyedWriteWraps(0, 'client connected'); 63 64 this.once('data', common.mustCall(ondata)); 65} 66 67function ondata() { 68 // 69 // Writing data to client socket 70 // 71 const write = () => { 72 let writeFinished = false; 73 this.write('f'.repeat(1280000), () => { 74 writeFinished = true; 75 }); 76 process.nextTick(() => { 77 if (writeFinished) { 78 // Synchronous finish, write more data immediately. 79 writeFinished = false; 80 write(); 81 } else { 82 // Asynchronous write; this is what we are here for. 83 onafterwrite(this); 84 } 85 }); 86 }; 87 write(); 88} 89 90function onafterwrite(self) { 91 checkDestroyedWriteWraps(1, 'client destroyed'); 92 self.end(); 93 94 checkDestroyedWriteWraps(1, 'client destroyed'); 95 96 // 97 // Closing server 98 // 99 server.close(common.mustCall(onserverClosed)); 100 checkDestroyedWriteWraps(1, 'server closing'); 101} 102 103function onserverClosed() { 104 checkDestroyedWriteWraps(1, 'server closed'); 105} 106 107process.on('exit', onexit); 108 109function onexit() { 110 hooks.disable(); 111 hooks.sanityCheck('WRITEWRAP'); 112 checkDestroyedWriteWraps(1, 'process exits'); 113} 114