Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add decompress interceptor #3274

Open
wants to merge 7 commits into
base: main
Choose a base branch
from
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
3 changes: 2 additions & 1 deletion index.js
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,8 @@ module.exports.createRedirectInterceptor = createRedirectInterceptor
module.exports.interceptors = {
redirect: require('./lib/interceptor/redirect'),
retry: require('./lib/interceptor/retry'),
dump: require('./lib/interceptor/dump')
dump: require('./lib/interceptor/dump'),
decompress: require('./lib/interceptor/decompress')
}

module.exports.buildConnector = buildConnector
Expand Down
131 changes: 131 additions & 0 deletions lib/interceptor/decompress.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,131 @@
'use strict'

const util = require('../core/util')
const DecoratorHandler = require('../handler/decorator-handler')
const zlib = require('node:zlib')
const { pipeline, finished } = require('node:stream')
const { createInflate } = require('../web/fetch/util')

const nullBodyStatus = [101, 204, 205, 304]

class DecompressHandler extends DecoratorHandler {
#handler
#opts

#inputStream = null
#trailers = null

constructor (opts, handler) {
super(handler)
this.#handler = handler
this.#opts = opts
}

adrianfalleiro marked this conversation as resolved.
Show resolved Hide resolved
onConnect (abort) {
this.#inputStream = null
this.#trailers = null
metcoder95 marked this conversation as resolved.
Show resolved Hide resolved
return this.#handler.onConnect(abort)
}

#onDecompressStreamFinished (err) {
if (err) {
this.#handler.onError(err)
} else {
this.#handler.onComplete(this.#trailers)
}
}

onHeaders (statusCode, rawHeaders, resume, statusMessage) {
const parsedHeaders = util.parseHeaders(rawHeaders)
const contentEncoding = parsedHeaders['content-encoding']
const requestEncodings = contentEncoding ? contentEncoding.split(',').map(e => e.trim().toLowerCase()) : []

const { method } = this.#opts

// https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Encoding
if (requestEncodings.length !== 0 && method !== 'HEAD' && method !== 'CONNECT' && !nullBodyStatus.includes(statusCode)) {
const decoders = []
for (let i = 0; i < requestEncodings.length; ++i) {
Copy link
Member

@tsctx tsctx Jun 18, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
for (let i = 0; i < requestEncodings.length; ++i) {
for (let i = requestEncodings.length - 1; i >= 0; --i) {

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The other way round, right?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah, I made the same changes #3343.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks, I'll come back to this PR this week

const requestEncoding = requestEncodings[i]
// https://www.rfc-editor.org/rfc/rfc9112.html#section-7.2
if ((requestEncoding === 'x-gzip' || requestEncoding === 'gzip')) {
decoders.push(zlib.createGunzip({
// Be less strict when decoding compressed responses, since sometimes
// servers send slightly invalid responses that are still accepted
// by common browsers.
// Always using Z_SYNC_FLUSH is what cURL does.
flush: zlib.constants.Z_SYNC_FLUSH,
finishFlush: zlib.constants.Z_SYNC_FLUSH
}))
} else if (requestEncoding === 'deflate') {
decoders.push(createInflate())
} else if (requestEncoding === 'br') {
decoders.push(zlib.createBrotliDecompress())
} else {
decoders.length = 0
break
}
}

if (decoders.length !== 0) {
const [firstDecoder, ...restDecoders] = decoders
this.#inputStream = firstDecoder
let outputStream = firstDecoder

if (restDecoders.length !== 0) {
outputStream = pipeline(
this.#inputStream,
...restDecoders,
this.#onDecompressStreamFinished.bind(this)
)
} else {
finished(
this.#inputStream,
this.#onDecompressStreamFinished.bind(this)
)
}

outputStream.on('data', (chunk) => {
if (!this.#handler.onData(chunk)) {
this.#inputStream.pause()
this.#inputStream.once('drain', () => this.#inputStream.resume())
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Those is wrong. Drain is signaled through the resume function sent to onHeaders

}
})
}
}

return this.#handler.onHeaders(
statusCode,
rawHeaders,
resume,
statusMessage
)
}

onData (chunk) {
if (this.#inputStream) {
return this.#inputStream.write(chunk)
}
return this.#handler.onData(chunk)
}

onComplete (trailers) {
if (this.#inputStream) {
this.#trailers = trailers
this.#inputStream.end()
return
}

return this.#handler.onComplete(trailers)
}
}

function createDecompressionInterceptor () {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We might need to support add the hinting of supported encoding in case implementers wants to limit this (I can only think for performance reasons).
They can pass a set of encodings supported, and the decompress decorator hints it using accept-encoding

return dispatch => {
return function Decompress (opts, handler) {
return dispatch(opts, new DecompressHandler(opts, handler))
}
}
}

module.exports = createDecompressionInterceptor
Loading