Skip to content

Commit

Permalink
fix: ensure we add an abort reason
Browse files Browse the repository at this point in the history
  • Loading branch information
wyattjoh committed Oct 18, 2023
1 parent 64c3374 commit 081c68f
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 8 deletions.
15 changes: 9 additions & 6 deletions packages/next/src/server/pipe-readable.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,14 @@ import type { ServerResponse } from 'node:http'

import './node-polyfill-web-streams'

import { createAbortController } from './web/spec-extension/adapters/next-request'
import {
ResponseAbortedName,
createAbortController,
} from './web/spec-extension/adapters/next-request'
import { DetachedPromise } from '../lib/detached-promise'

export function isAbortError(e: any): e is Error & { name: 'AbortError' } {
return e?.name === 'AbortError'
return e?.name === 'AbortError' || e?.name === ResponseAbortedName
}

function createWriterFromResponse(
Expand Down Expand Up @@ -66,7 +69,7 @@ function createWriterFromResponse(
}
} catch (err) {
res.end()
throw err
throw new Error('failed to write chunk to response', { cause: err })
}
},
abort: (err) => {
Expand Down Expand Up @@ -101,8 +104,8 @@ export async function pipeToNodeResponse(
await readable.pipeTo(writer, { signal: controller.signal })
} catch (err: any) {
// If this isn't related to an abort error, re-throw it.
if (!isAbortError(err)) {
throw err
}
if (isAbortError(err)) return

throw new Error('failed to pipe response', { cause: err })
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,11 @@ import { getRequestMeta } from '../../../request-meta'
import { fromNodeOutgoingHttpHeaders } from '../../utils'
import { NextRequest } from '../request'

export const ResponseAbortedName = 'ResponseAborted'
export class ResponseAborted extends Error {
public readonly name = ResponseAbortedName
}

/**
* Creates an AbortController tied to the closing of a ServerResponse (or other
* appropriate Writable).
Expand All @@ -23,7 +28,7 @@ export function createAbortController(response: Writable): AbortController {
response.once('close', () => {
if (response.writableFinished) return

controller.abort()
controller.abort(new ResponseAborted())
})

return controller
Expand All @@ -39,7 +44,9 @@ export function createAbortController(response: Writable): AbortController {
*/
export function signalFromNodeResponse(response: Writable): AbortSignal {
const { errored, destroyed } = response
if (errored || destroyed) return AbortSignal.abort(errored)
if (errored || destroyed) {
return AbortSignal.abort(errored ?? new ResponseAborted())
}

const { signal } = createAbortController(response)
return signal
Expand Down

0 comments on commit 081c68f

Please sign in to comment.