1'use strict'; 2const common = require('../common'); 3 4common.skipIfInspectorDisabled(); 5 6const { Worker, isMainThread, parentPort, workerData } = 7 require('worker_threads'); 8 9if (isMainThread || workerData !== 'launched by test') { 10 common.skipIfWorker(); 11} 12 13const { Session } = require('inspector'); 14 15const MAX_DEPTH = 3; 16 17let rootWorker = null; 18 19const runTest = common.mustCall(function() { 20 let reportedWorkersCount = 0; 21 const session = new Session(); 22 session.connect(); 23 session.on('NodeWorker.attachedToWorker', common.mustCall( 24 ({ params: { workerInfo } }) => { 25 console.log(`Worker ${workerInfo.title} was reported`); 26 if (++reportedWorkersCount === MAX_DEPTH) { 27 rootWorker.postMessage({ done: true }); 28 } 29 }, MAX_DEPTH)); 30 session.post('NodeWorker.enable', { waitForDebuggerOnStart: false }); 31}); 32 33function processMessage({ child }) { 34 console.log(`Worker ${child} is running`); 35 if (child === MAX_DEPTH) { 36 runTest(); 37 } 38} 39 40function workerCallback(message) { 41 parentPort.postMessage(message); 42} 43 44function startWorker(depth, messageCallback) { 45 const worker = new Worker(__filename, { workerData: 'launched by test' }); 46 worker.on('message', messageCallback); 47 worker.postMessage({ depth }); 48 return worker; 49} 50 51function runMainThread() { 52 rootWorker = startWorker(1, processMessage); 53} 54 55function runChildWorkerThread() { 56 let worker = null; 57 parentPort.on('message', ({ child, depth, done }) => { 58 if (done) { 59 if (worker) { 60 worker.postMessage({ done: true }); 61 } 62 parentPort.close(); 63 } else if (depth) { 64 parentPort.postMessage({ child: depth }); 65 if (depth < MAX_DEPTH) { 66 worker = startWorker(depth + 1, workerCallback); 67 } 68 } else if (child) { 69 parentPort.postMessage({ child }); 70 } 71 }); 72} 73 74if (isMainThread) { 75 runMainThread(); 76} else { 77 runChildWorkerThread(); 78} 79