-
-
Notifications
You must be signed in to change notification settings - Fork 674
Decompression Interceptor #4317
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
Merged
Merged
Changes from all commits
Commits
Show all changes
31 commits
Select commit
Hold shift + click to select a range
9c4b391
undici vs fetch
FelixVaughan d9a9921
snackin
FelixVaughan cbcbe2a
nothing serious
FelixVaughan 58553bc
todo: tests
FelixVaughan fa633ec
testing
FelixVaughan f0e3f6a
resolve merge conflict
FelixVaughan c640901
cleanup
FelixVaughan f0266eb
Update lib/interceptor/decompress.js
FelixVaughan 572eb75
resolve conflict
FelixVaughan 1accabb
documentation
FelixVaughan d5bf430
formatting
FelixVaughan 74cc73f
pr suggestions
FelixVaughan ae7847c
pr suggestions as well as zstd support
FelixVaughan 8294096
update documatation
FelixVaughan d229312
personal pedancy
FelixVaughan af7c01b
pr suggestions
FelixVaughan 88c6170
tidied up decompression chaining logic
FelixVaughan 13783dc
wip
FelixVaughan 8d003fb
pr suggestions and tests
FelixVaughan fa8db99
skip createZstdCompress tests when unavailable (pre v22)
FelixVaughan 8ca18ec
tidy up
FelixVaughan 08d34d1
conditional usage of createZstdDecompress
FelixVaughan a411ae1
added some comments (mostly to re-trigger CI/CD)
FelixVaughan 083073c
Added tests with fetch()
FelixVaughan 70a291d
refactored createDecompressionChain to use a basic for loop
FelixVaughan dddd2a0
Merge branch 'main' of github.com:nodejs/undici into decomp-interceptor
FelixVaughan 9d5255a
apply changes
Uzlopak 87fb219
improved jsdocs, removed non-critical handler return statements
FelixVaughan 2bc4323
experimental flag in dispatcher.md for decompress
FelixVaughan 00d869e
plain object use
FelixVaughan c07802d
readble event
FelixVaughan File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,253 @@ | ||
| 'use strict' | ||
|
|
||
| const { createInflate, createGunzip, createBrotliDecompress, createZstdDecompress } = require('node:zlib') | ||
| const { pipeline } = require('node:stream') | ||
| const DecoratorHandler = require('../handler/decorator-handler') | ||
|
|
||
| /** @typedef {import('node:stream').Transform} Transform */ | ||
| /** @typedef {import('node:stream').Transform} Controller */ | ||
| /** @typedef {Transform&import('node:zlib').Zlib} DecompressorStream */ | ||
|
|
||
| /** @type {Record<string, () => DecompressorStream>} */ | ||
| const supportedEncodings = { | ||
| gzip: createGunzip, | ||
| 'x-gzip': createGunzip, | ||
| br: createBrotliDecompress, | ||
| deflate: createInflate, | ||
| compress: createInflate, | ||
| 'x-compress': createInflate, | ||
| ...(createZstdDecompress ? { zstd: createZstdDecompress } : {}) | ||
| } | ||
|
|
||
| const defaultSkipStatusCodes = /** @type {const} */ ([204, 304]) | ||
|
|
||
| let warningEmitted = /** @type {boolean} */ (false) | ||
|
|
||
| /** | ||
| * @typedef {Object} DecompressHandlerOptions | ||
| * @property {number[]|Readonly<number[]>} [skipStatusCodes=[204, 304]] - List of status codes to skip decompression for | ||
| * @property {boolean} [skipErrorResponses] - Whether to skip decompression for error responses (status codes >= 400) | ||
| */ | ||
|
|
||
| class DecompressHandler extends DecoratorHandler { | ||
metcoder95 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| /** @type {Transform[]} */ | ||
| #decompressors = [] | ||
| /** @type {NodeJS.WritableStream&NodeJS.ReadableStream|null} */ | ||
| #pipelineStream | ||
| /** @type {Readonly<number[]>} */ | ||
| #skipStatusCodes | ||
| /** @type {boolean} */ | ||
| #skipErrorResponses | ||
|
|
||
| constructor (handler, { skipStatusCodes = defaultSkipStatusCodes, skipErrorResponses = true } = {}) { | ||
| super(handler) | ||
| this.#skipStatusCodes = skipStatusCodes | ||
| this.#skipErrorResponses = skipErrorResponses | ||
| } | ||
|
|
||
| /** | ||
| * Determines if decompression should be skipped based on encoding and status code | ||
| * @param {string} contentEncoding - Content-Encoding header value | ||
| * @param {number} statusCode - HTTP status code of the response | ||
| * @returns {boolean} - True if decompression should be skipped | ||
| */ | ||
| #shouldSkipDecompression (contentEncoding, statusCode) { | ||
| if (!contentEncoding || statusCode < 200) return true | ||
| if (this.#skipStatusCodes.includes(statusCode)) return true | ||
| if (this.#skipErrorResponses && statusCode >= 400) return true | ||
| return false | ||
| } | ||
|
|
||
| /** | ||
| * Creates a chain of decompressors for multiple content encodings | ||
| * | ||
| * @param {string} encodings - Comma-separated list of content encodings | ||
| * @returns {Array<DecompressorStream>} - Array of decompressor streams | ||
| */ | ||
| #createDecompressionChain (encodings) { | ||
| const parts = encodings.split(',') | ||
|
|
||
| /** @type {DecompressorStream[]} */ | ||
| const decompressors = [] | ||
|
|
||
| for (let i = parts.length - 1; i >= 0; i--) { | ||
| const encoding = parts[i].trim() | ||
| if (!encoding) continue | ||
|
|
||
| if (!supportedEncodings[encoding]) { | ||
| decompressors.length = 0 // Clear if unsupported encoding | ||
| return decompressors // Unsupported encoding | ||
| } | ||
|
|
||
| decompressors.push(supportedEncodings[encoding]()) | ||
| } | ||
|
|
||
| return decompressors | ||
| } | ||
mcollina marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
|
||
| /** | ||
| * Sets up event handlers for a decompressor stream using readable events | ||
| * @param {DecompressorStream} decompressor - The decompressor stream | ||
| * @param {Controller} controller - The controller to coordinate with | ||
| * @returns {void} | ||
| */ | ||
| #setupDecompressorEvents (decompressor, controller) { | ||
| decompressor.on('readable', () => { | ||
| let chunk | ||
| while ((chunk = decompressor.read()) !== null) { | ||
| const result = super.onResponseData(controller, chunk) | ||
| if (result === false) { | ||
| break | ||
| } | ||
| } | ||
| }) | ||
|
|
||
| decompressor.on('error', (error) => { | ||
| super.onResponseError(controller, error) | ||
| }) | ||
| } | ||
|
|
||
| /** | ||
| * Sets up event handling for a single decompressor | ||
| * @param {Controller} controller - The controller to handle events | ||
| * @returns {void} | ||
| */ | ||
| #setupSingleDecompressor (controller) { | ||
| const decompressor = this.#decompressors[0] | ||
| this.#setupDecompressorEvents(decompressor, controller) | ||
|
|
||
| decompressor.on('end', () => { | ||
| super.onResponseEnd(controller, {}) | ||
| }) | ||
| } | ||
|
|
||
| /** | ||
| * Sets up event handling for multiple chained decompressors using pipeline | ||
| * @param {Controller} controller - The controller to handle events | ||
| * @returns {void} | ||
| */ | ||
| #setupMultipleDecompressors (controller) { | ||
| const lastDecompressor = this.#decompressors[this.#decompressors.length - 1] | ||
| this.#setupDecompressorEvents(lastDecompressor, controller) | ||
|
|
||
| this.#pipelineStream = pipeline(this.#decompressors, (err) => { | ||
| if (err) { | ||
| super.onResponseError(controller, err) | ||
| return | ||
| } | ||
| super.onResponseEnd(controller, {}) | ||
| }) | ||
| } | ||
|
|
||
| /** | ||
| * Cleans up decompressor references to prevent memory leaks | ||
| * @returns {void} | ||
| */ | ||
| #cleanupDecompressors () { | ||
| this.#decompressors.length = 0 | ||
| this.#pipelineStream = null | ||
| } | ||
|
|
||
| /** | ||
| * @param {Controller} controller | ||
| * @param {number} statusCode | ||
| * @param {Record<string, string | string[] | undefined>} headers | ||
| * @param {string} statusMessage | ||
| * @returns {void} | ||
| */ | ||
| onResponseStart (controller, statusCode, headers, statusMessage) { | ||
| const contentEncoding = headers['content-encoding'] | ||
|
|
||
| // If content encoding is not supported or status code is in skip list | ||
| if (this.#shouldSkipDecompression(contentEncoding, statusCode)) { | ||
| return super.onResponseStart(controller, statusCode, headers, statusMessage) | ||
| } | ||
|
|
||
| const decompressors = this.#createDecompressionChain(contentEncoding.toLowerCase()) | ||
|
|
||
| if (decompressors.length === 0) { | ||
| this.#cleanupDecompressors() | ||
| return super.onResponseStart(controller, statusCode, headers, statusMessage) | ||
| } | ||
|
|
||
| this.#decompressors = decompressors | ||
|
|
||
| // Remove compression headers since we're decompressing | ||
| const { 'content-encoding': _, 'content-length': __, ...newHeaders } = headers | ||
|
|
||
| if (this.#decompressors.length === 1) { | ||
| this.#setupSingleDecompressor(controller) | ||
| } else { | ||
| this.#setupMultipleDecompressors(controller) | ||
| } | ||
|
|
||
| super.onResponseStart(controller, statusCode, newHeaders, statusMessage) | ||
| } | ||
|
|
||
| /** | ||
| * @param {Controller} controller | ||
| * @param {Buffer} chunk | ||
| * @returns {void} | ||
| */ | ||
| onResponseData (controller, chunk) { | ||
| if (this.#decompressors.length > 0) { | ||
| this.#decompressors[0].write(chunk) | ||
| return | ||
| } | ||
| super.onResponseData(controller, chunk) | ||
| } | ||
|
|
||
| /** | ||
| * @param {Controller} controller | ||
| * @param {Record<string, string | string[]> | undefined} trailers | ||
| * @returns {void} | ||
| */ | ||
| onResponseEnd (controller, trailers) { | ||
| if (this.#decompressors.length > 0) { | ||
| this.#decompressors[0].end() | ||
| this.#cleanupDecompressors() | ||
| return | ||
| } | ||
| super.onResponseEnd(controller, trailers) | ||
| } | ||
|
|
||
| /** | ||
| * @param {Controller} controller | ||
| * @param {Error} err | ||
| * @returns {void} | ||
| */ | ||
| onResponseError (controller, err) { | ||
| if (this.#decompressors.length > 0) { | ||
| for (const decompressor of this.#decompressors) { | ||
| decompressor.destroy(err) | ||
| } | ||
| this.#cleanupDecompressors() | ||
| } | ||
| super.onResponseError(controller, err) | ||
| } | ||
| } | ||
|
|
||
| /** | ||
| * Creates a decompression interceptor for HTTP responses | ||
| * @param {DecompressHandlerOptions} [options] - Options for the interceptor | ||
| * @returns {Function} - Interceptor function | ||
| */ | ||
| function createDecompressInterceptor (options = {}) { | ||
| // Emit experimental warning only once | ||
| if (!warningEmitted) { | ||
| process.emitWarning( | ||
| 'DecompressInterceptor is experimental and subject to change', | ||
| 'ExperimentalWarning' | ||
| ) | ||
| warningEmitted = true | ||
| } | ||
|
|
||
| return (dispatch) => { | ||
| return (opts, handler) => { | ||
| const decompressHandler = new DecompressHandler(handler, options) | ||
| return dispatch(opts, decompressHandler) | ||
| } | ||
| } | ||
| } | ||
|
|
||
| module.exports = createDecompressInterceptor | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.