Skip to content

extractBody fixes 2 - #5926

Merged
KhafraDev merged 1 commit into
nodejs:mainfrom
KhafraDev:fetch/extractBody-fixes-2
Sep 30, 2026
Merged

KhafraDev merged 1 commit into
nodejs:mainfrom
KhafraDev:fetch/extractBody-fixes-2

Conversation

@KhafraDev

Copy link
Copy Markdown
Member

Closes #5923 which isn't a bug, but this approach is better than before, any ways

This relates to...

Rationale

Changes

Features

Bug Fixes

Breaking Changes and Deprecations

Status

@codecov-commenter

codecov-commenter commented Sep 29, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 94.07%. Comparing base (da911f0) to head (56c2336).

Additional details and impacted files
@@            Coverage Diff             @@
##             main    #5926      +/-   ##
==========================================
- Coverage   94.07%   94.07%   -0.01%     
==========================================
  Files         110      110              
  Lines       40293    40302       +9     
==========================================
+ Hits        37905    37913       +8     
- Misses       2388     2389       +1     

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@TechDev009

Copy link
Copy Markdown

This also fixes a crash that is on main and in every release since 7.20.0 (#4791): cancelling a FormData body ends in an unhandled rejection, so the process exits.

const { Request, FormData } = require('undici')

const form = new FormData()
form.append('file', new File([new Uint8Array(8000)], 'a.bin'))

new Request('http://localhost', { method: 'POST', body: form }).body.cancel()
TypeError [ERR_INVALID_STATE]: Invalid state: ReadableStream is already closed
    at ReadableByteStreamController.enqueue (node:internal/webstreams/readablestream:1318:13)
    at lib/web/fetch/body.js:233:24

The detached loop only checks isErrored(stream). A cancelled stream is closed, not errored, so the next controller.enqueue throws and nothing awaits it. new Response(form) does the same, and so does a cancel after a few reads. 7.16.0 is clean; 7.30.0, 8.9.0 (the global fetch in Node 26.6), 8.11.2 and main at da911f0 all reproduce.

On this branch at 56c2336 the repro is clean on Node 24 and 26, since cancel() now returns the iterator.

Nothing in test/fetch covers the cancel path. Here is a test in case you want it in this PR: 4 of its 5 cases fail on main, all pass here. I can also send it as a follow-up PR once this lands.

test/fetch/formdata-body-cancel.js
'use strict'

const { test } = require('node:test')
const { Request, Response, FormData } = require('../..')

function makeFormData () {
  const form = new FormData()
  form.append('title', 'a')
  form.append('a', new File([new Uint8Array(8000)], 'a.bin'))
  form.append('b', new File([new Uint8Array(8000)], 'b.bin'))
  return form
}

// The parts of a FormData body are enqueued in the background. Cancelling the
// body closes the stream, and the next enqueue used to throw ERR_INVALID_STATE
// as an unhandled rejection.
async function cancelAfter (t, body, reads) {
  const unhandled = []
  const onUnhandledRejection = (err) => unhandled.push(err)
  process.on('unhandledRejection', onUnhandledRejection)
  t.after(() => process.off('unhandledRejection', onUnhandledRejection))

  const reader = body.getReader()
  for (let i = 0; i < reads; i++) {
    const { done } = await reader.read()
    t.assert.strictEqual(done, false)
  }
  await reader.cancel()

  // Let the background enqueue run against the closed stream.
  await new Promise((resolve) => setTimeout(resolve, 50))
  t.assert.deepStrictEqual(unhandled, [])
}

test('cancelling an unread FormData request body does not reject', async (t) => {
  const request = new Request('http://localhost', { method: 'POST', body: makeFormData() })
  await cancelAfter(t, request.body, 0)
})

test('cancelling a partially read FormData request body does not reject', async (t) => {
  const request = new Request('http://localhost', { method: 'POST', body: makeFormData() })
  await cancelAfter(t, request.body, 2)
})

test('cancelling an unread FormData response body does not reject', async (t) => {
  await cancelAfter(t, new Response(makeFormData()).body, 0)
})

test('cancelling a partially read FormData response body does not reject', async (t) => {
  await cancelAfter(t, new Response(makeFormData()).body, 2)
})

test('a FormData body that is not cancelled is still read in full', async (t) => {
  const request = new Request('http://localhost', { method: 'POST', body: makeFormData() })
  const form = await request.formData()

  t.assert.strictEqual(form.get('title'), 'a')
  t.assert.strictEqual(form.get('a').size, 8000)
  t.assert.strictEqual(form.get('b').size, 8000)
})

@KhafraDev
KhafraDev merged commit e049c53 into nodejs:main Sep 30, 2026
36 of 38 checks passed
@KhafraDev
KhafraDev deleted the fetch/extractBody-fixes-2 branch September 30, 2026 13:46
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

fetch: a FormData body is read whole into memory before it is sent (no backpressure since 7.20.0)

4 participants