|
| 1 | +'use strict'; |
| 2 | +const common = require('../common'); |
| 3 | +if (!common.hasCrypto) { common.skip('missing crypto'); } |
| 4 | + |
| 5 | +const { Readable } = require('stream'); |
| 6 | +const process = require('process'); |
| 7 | +const { randomBytes } = require('crypto'); |
| 8 | +const assert = require('assert'); |
| 9 | + |
| 10 | +// Based on: https://github.com/nodejs/node/issues/46347#issuecomment-1413886707 |
| 11 | +// edit: make it cross-platform as /dev/urandom is not available on Windows |
| 12 | +{ |
| 13 | + let currentMemoryUsage = process.memoryUsage().arrayBuffers; |
| 14 | + |
| 15 | + // We initialize a stream, but not start consuming it |
| 16 | + const randomNodeStream = new Readable({ |
| 17 | + read(size) { |
| 18 | + randomBytes(size, (err, buffer) => { |
| 19 | + if (err) { |
| 20 | + // If an error occurs, emit an 'error' event |
| 21 | + this.emit('error', err); |
| 22 | + return; |
| 23 | + } |
| 24 | + |
| 25 | + // Push the random bytes to the stream |
| 26 | + this.push(buffer); |
| 27 | + }); |
| 28 | + } |
| 29 | + }); |
| 30 | + // after 2 seconds, it'll get converted to web stream |
| 31 | + let randomWebStream; |
| 32 | + |
| 33 | + // We check memory usage every second |
| 34 | + // since it's a stream, it shouldn't be higher than the chunk size |
| 35 | + const reportMemoryUsage = () => { |
| 36 | + const { arrayBuffers } = process.memoryUsage(); |
| 37 | + currentMemoryUsage = arrayBuffers; |
| 38 | + |
| 39 | + assert(currentMemoryUsage <= 256 * 1024 * 1024); |
| 40 | + }; |
| 41 | + setInterval(reportMemoryUsage, 1000); |
| 42 | + |
| 43 | + // after 1 second we use Readable.toWeb |
| 44 | + // memory usage should stay pretty much the same since it's still a stream |
| 45 | + setTimeout(() => { |
| 46 | + randomWebStream = Readable.toWeb(randomNodeStream); |
| 47 | + }, 1000); |
| 48 | + |
| 49 | + // after 2 seconds we start consuming the stream |
| 50 | + // memory usage will grow, but the old chunks should be garbage-collected pretty quickly |
| 51 | + setTimeout(async () => { |
| 52 | + // eslint-disable-next-line no-unused-vars |
| 53 | + for await (const _ of randomWebStream) { |
| 54 | + // Do nothing, just let the stream flow |
| 55 | + } |
| 56 | + }, 2000); |
| 57 | + |
| 58 | + setTimeout(() => { |
| 59 | + // Test considered passed if we don't crash |
| 60 | + process.exit(0); |
| 61 | + }, 5000); |
| 62 | +} |
0 commit comments