Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 17 additions & 3 deletions lib/web/fetch/util.js
Original file line number Diff line number Diff line change
Expand Up @@ -1248,6 +1248,8 @@ function buildContentRange (rangeStart, rangeEnd, fullLength) {
// raw deflate stream.
class InflateStream extends Transform {
#zlibOptions
/** @type {zlib.Inflate | zlib.InflateRaw | undefined} */
#inflate

/** @param {zlib.ZlibOptions} [zlibOptions] */
constructor (zlibOptions) {
Expand All @@ -1265,14 +1267,26 @@ class InflateStream extends Transform {
? zlib.createInflate(this.#zlibOptions)
: zlib.createInflateRaw(this.#zlibOptions)

this._inflateStream.on('data', this.push.bind(this))
this._inflateStream.on('end', () => this.push(null))
this._inflateStream.on('error', (err) => this.destroy(err))
const inflate = this.#inflate = this._inflateStream
// Pause the inner stream while this stream's readable buffer is full, so
// an unconsumed body stays bounded like with the zlib transform streams.
inflate.on('data', (data) => {
if (!this.push(data)) {
inflate.pause()
}
})
inflate.on('end', () => this.push(null))
inflate.on('error', (err) => this.destroy(err))
}

this._inflateStream.write(chunk, encoding, callback)
}

_read (size) {
this.#inflate?.resume()
super._read(size)
}

_final (callback) {
if (this._inflateStream) {
this._inflateStream.end()
Expand Down
20 changes: 20 additions & 0 deletions test/fetch/util.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
'use strict'

const { describe, test } = require('node:test')
const zlib = require('node:zlib')
const util = require('../../lib/web/fetch/util')
const { HeadersList } = require('../../lib/web/fetch/headers')

Expand Down Expand Up @@ -310,3 +311,22 @@ describe('isOriginIPPotentiallyTrustworthy()', () => {
})
})
})

describe('createInflate', () => {
for (const [name, deflate] of [['zlib', zlib.deflateSync], ['raw', zlib.deflateRawSync]]) {
test(`buffers a bounded amount when not read (${name} deflate)`, async (t) => {
const size = 16 * 1024 * 1024
const inflate = util.createInflate()
inflate.end(deflate(Buffer.alloc(size)))

await new Promise((resolve) => setTimeout(resolve, 100))
t.assert.ok(inflate.readableLength < 1024 * 1024, `buffered ${inflate.readableLength} bytes`)

let total = 0
for await (const chunk of inflate) {
total += chunk.length
}
t.assert.strictEqual(total, size)
})
}
})
Loading