Unverified Commit 75718952 authored by Shohei Maeda's avatar Shohei Maeda Committed by GitHub

Handle cancellation errors during response clone cleanup (#100961)

## Summary

A response body can fail after `fetch()` resolves, for example when an
upstream connection closes. Even if the caller catches the body-read
error, garbage-collection cleanup of an unused response clone can call
`cancel()` on its already-errored stream.

That cancellation rejects, and the existing `.then(noop)` leaves the
rejection unhandled. Depending on the runtime’s unhandled-rejection
handling, this can terminate the process.

Use `.catch(noop)` to handle cancellation failures during cleanup. The
original body-read error still reaches the caller.

Related: https://github.com/vrv/vercel-runtime-cache-cancel-repro
parent 65e4a5ed
...@@ -6,7 +6,9 @@ if (globalThis.FinalizationRegistry) { ...@@ -6,7 +6,9 @@ if (globalThis.FinalizationRegistry) {
registry = new FinalizationRegistry((weakRef: WeakRef<ReadableStream>) => { registry = new FinalizationRegistry((weakRef: WeakRef<ReadableStream>) => {
const stream = weakRef.deref() const stream = weakRef.deref()
if (stream && !stream.locked) { if (stream && !stream.locked) {
stream.cancel('Response object has been garbage collected').then(noop) // Cleanup can run after the body has errored, even when its reader caught
// the error. Keep this best-effort cancellation from becoming unhandled.
stream.cancel('Response object has been garbage collected').catch(noop)
} }
}) })
} }
......
/**
* @jest-environment node
*/
describe('cloneResponse', () => {
let cloneResponse: typeof import('../../packages/next/src/server/lib/clone-response').cloneResponse
let finalize: (ref: WeakRef<ReadableStream>) => void
let register: jest.Mock
beforeEach(() => {
register = jest.fn()
// Control finalization without depending on when the garbage collector runs.
const registry = jest
.spyOn(globalThis, 'FinalizationRegistry')
.mockImplementation((callback) => {
finalize = callback
return { register } as unknown as FinalizationRegistry<unknown>
})
try {
jest.isolateModules(() => {
cloneResponse =
require('../../packages/next/src/server/lib/clone-response').cloneResponse
})
} finally {
registry.mockRestore()
}
})
it('handles cleanup failure after the consumer catches a body error', async () => {
let controller: ReadableStreamDefaultController
const original = new Response(
new ReadableStream({
start(value) {
controller = value
},
})
)
const [consumed, unused] = cloneResponse(original)
const read = consumed.json()
const error = new TypeError('terminated')
controller!.error(error)
await expect(read).rejects.toBe(error)
expect(unused.body!.locked).toBe(false)
const unusedRef = register.mock.calls.find(
([response]) => response === unused
)![1]
finalize(unusedRef)
// An ignored cancellation rejection is reported on the next event-loop turn.
await new Promise<void>((resolve) => setImmediate(resolve))
})
it('keeps both cloned bodies independently readable', async () => {
const [first, second] = cloneResponse(new Response('value'))
expect(await Promise.all([first.text(), second.text()])).toEqual([
'value',
'value',
])
})
})
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment