From 693de217b030816f574d6e4cb505ee2e77b21c29 Mon Sep 17 00:00:00 2001 From: Szymon Marczak <36894700+szmarczak@users.noreply.github.com> Date: Fri, 2 Sep 2022 19:47:41 +0200 Subject: [PATCH] Attempt to skip emitting uploadProgress after destroy --- source/core/index.ts | 6 ++++-- test/post.ts | 28 ++++++++++++++++++++++++++++ 2 files changed, 32 insertions(+), 2 deletions(-) diff --git a/source/core/index.ts b/source/core/index.ts index 69dcb151e..983aff099 100644 --- a/source/core/index.ts +++ b/source/core/index.ts @@ -483,7 +483,8 @@ export default class Request extends Duplex implements RequestEvents { return; } - if (!error) { + // The `!destroyed` check is required to prevent `uploadProgress` being emitted after the stream was destroyed + if (!error && this._request!.destroyed) { this._bodySize = this._uploadedSize; this.emit('uploadProgress', this.uploadProgress); @@ -1178,7 +1179,8 @@ export default class Request extends Duplex implements RequestEvents { } this._request.write(chunk, encoding!, (error?: Error | null) => { // eslint-disable-line @typescript-eslint/ban-types - if (!error) { + // The `!destroyed` check is required to prevent `uploadProgress` being emitted after the stream was destroyed + if (!error && !this._request!.destroyed) { this._uploadedSize += Buffer.byteLength(chunk, encoding); const progress = this.uploadProgress; diff --git a/test/post.ts b/test/post.ts index 96a8960c2..b5eb4f763 100644 --- a/test/post.ts +++ b/test/post.ts @@ -440,3 +440,31 @@ test('formdata retry', withServer, async (t, server, got) => { message: 'Cannot retry with consumed body stream', }); }); + +test('does not emit uploadProgress after cancelation', withServer, async (t, server, got) => { + server.post('/', () => {}); + + const stream = got.stream.post(); + + stream.once('uploadProgress', () => { // 0% + stream.once('uploadProgress', () => { // 'foo' + stream.write('bar'); + + process.nextTick(() => { + process.nextTick(() => { + stream.on('uploadProgress', () => { + t.fail('Emitted uploadProgress after cancelation'); + }); + + stream.destroy(); + }); + }); + }); + }); + + stream.write('foo'); + + await pEvent(stream, 'close'); + + t.pass(); +});