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鈥檒l occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: exit loop early if request was aborted #1396

Merged
merged 1 commit into from May 2, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
5 changes: 5 additions & 0 deletions lib/fetch/index.js
Expand Up @@ -1827,6 +1827,11 @@ async function httpNetworkFetch (
let bytes
try {
const { done, value } = await fetchParams.controller.next()

if (isAborted(fetchParams)) {
break
}

bytes = done ? undefined : value
} catch (err) {
if (fetchParams.controller.ended && !timingInfo.encodedBodySize) {
Expand Down
59 changes: 59 additions & 0 deletions test/fetch/abort.js
@@ -0,0 +1,59 @@
'use strict'

const { test } = require('tap')
const { fetch } = require('../..')
const { createServer } = require('http')
const { once } = require('events')

/* global AbortController */

test('parallel fetch with the same AbortController works as expected', async (t) => {
const body = {
fixes: 1389,
bug: 'Ensure request is not aborted before enqueueing bytes into stream.'
}

const server = createServer((req, res) => {
res.statusCode = 200
res.end(JSON.stringify(body))
})

t.teardown(server.close.bind(server))

const abortController = new AbortController()

async function makeRequest () {
const result = await fetch(`http://localhost:${server.address().port}`, {
signal: abortController.signal
}).then(response => response.json())

abortController.abort()
return result
}

server.listen(0)
await once(server, 'listening')

const requests = Array.from({ length: 10 }, makeRequest)
const result = await Promise.allSettled(requests)

// since the requests are running parallel, any of them could resolve first.
// therefore we cannot rely on the order of the requests sent.
const { resolved, rejected } = result.reduce((a, b) => {
if (b.status === 'rejected') {
a.rejected.push(b)
} else {
a.resolved.push(b)
}

return a
}, { resolved: [], rejected: [] })

t.equal(rejected.length, 9) // out of 10 requests, only 1 should succeed
t.equal(resolved.length, 1)

t.ok(rejected.every(rej => rej.reason?.code === 'ABORT_ERR'))
t.same(resolved[0].value, body)

t.end()
})