1'use strict'; 2const common = require('../common'); 3const assert = require('assert'); 4const v8 = require('v8'); 5const { Worker, resourceLimits, isMainThread } = require('worker_threads'); 6 7if (isMainThread) { 8 assert.deepStrictEqual(resourceLimits, {}); 9} 10 11const testResourceLimits = { 12 maxOldGenerationSizeMb: 16, 13 maxYoungGenerationSizeMb: 4, 14 codeRangeSizeMb: 16, 15 stackSizeMb: 1, 16}; 17 18// Do not use isMainThread so that this test itself can be run inside a Worker. 19if (!process.env.HAS_STARTED_WORKER) { 20 process.env.HAS_STARTED_WORKER = 1; 21 const w = new Worker(__filename, { resourceLimits: testResourceLimits }); 22 assert.deepStrictEqual(w.resourceLimits, testResourceLimits); 23 w.on('exit', common.mustCall((code) => { 24 assert.strictEqual(code, 1); 25 assert.deepStrictEqual(w.resourceLimits, {}); 26 })); 27 w.on('error', common.expectsError({ 28 code: 'ERR_WORKER_OUT_OF_MEMORY', 29 message: 'Worker terminated due to reaching memory limit: ' + 30 'JS heap out of memory' 31 })); 32 return; 33} 34 35assert.deepStrictEqual(resourceLimits, testResourceLimits); 36const array = []; 37while (true) { 38 // Leave 10 % wiggle room here. 39 const usedMB = v8.getHeapStatistics().used_heap_size / 1024 / 1024; 40 assert(usedMB < resourceLimits.maxOldGenerationSizeMb * 1.1); 41 42 let seenSpaces = 0; 43 for (const { space_name, space_size } of v8.getHeapSpaceStatistics()) { 44 if (space_name === 'new_space') { 45 seenSpaces++; 46 assert( 47 space_size / 1024 / 1024 < resourceLimits.maxYoungGenerationSizeMb * 2); 48 } else if (space_name === 'old_space') { 49 seenSpaces++; 50 assert(space_size / 1024 / 1024 < resourceLimits.maxOldGenerationSizeMb); 51 } else if (space_name === 'code_space') { 52 seenSpaces++; 53 assert(space_size / 1024 / 1024 < resourceLimits.codeRangeSizeMb); 54 } 55 } 56 assert.strictEqual(seenSpaces, 3); 57 58 for (let i = 0; i < 100; i++) 59 array.push([array]); 60} 61