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 const usedMB = v8.getHeapStatistics().used_heap_size / 1024 / 1024; 39 const maxReservedSize = resourceLimits.maxOldGenerationSizeMb + 40 resourceLimits.maxYoungGenerationSizeMb; 41 assert(usedMB < maxReservedSize); 42 43 let seenSpaces = 0; 44 for (const { space_name, space_size } of v8.getHeapSpaceStatistics()) { 45 if (space_name === 'new_space') { 46 seenSpaces++; 47 assert( 48 space_size / 1024 / 1024 < resourceLimits.maxYoungGenerationSizeMb * 2); 49 } else if (space_name === 'old_space') { 50 seenSpaces++; 51 assert(space_size / 1024 / 1024 < resourceLimits.maxOldGenerationSizeMb); 52 } else if (space_name === 'code_space') { 53 seenSpaces++; 54 assert(space_size / 1024 / 1024 < resourceLimits.codeRangeSizeMb); 55 } 56 } 57 assert.strictEqual(seenSpaces, 3); 58 59 for (let i = 0; i < 100; i++) 60 array.push([array]); 61} 62