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’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(fetch): respect "abort" event on the request signal #394

Merged
merged 15 commits into from
Sep 2, 2023
Merged
Show file tree
Hide file tree
Changes from 7 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 28 additions & 0 deletions src/interceptors/ClientRequest/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import http from 'http'
import { HttpServer } from '@open-draft/test-server/http'
import { DeferredPromise } from '@open-draft/deferred-promise'
import { ClientRequestInterceptor } from '.'
import { sleep } from '../../../test/helpers'

const httpServer = new HttpServer((app) => {
app.get('/', (_req, res) => {
Expand Down Expand Up @@ -55,3 +56,30 @@ it('forbids calling "respondWith" multiple times for the same request', async ()
expect(response.statusCode).toBe(200)
expect(response.statusMessage).toBe('')
})


it('abort the request if the abort signal is emitted', async () => {
const requestUrl = httpServer.http.url('/')

const requestEmitted = new DeferredPromise<void>()
interceptor.on('request', async function delayedResponse({ request }) {
requestEmitted.resolve()
await sleep(10000)
request.respondWith(new Response())
})

const abortController = new AbortController()
const request = http.get(requestUrl, { signal: abortController.signal })

await requestEmitted

abortController.abort()

const requestAborted = new DeferredPromise<void>()
request.on('error', function(err) {
expect(err.name).toEqual('AbortError')
requestAborted.resolve()
})

await requestAborted
})
16 changes: 11 additions & 5 deletions src/interceptors/fetch/index.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { DeferredPromise } from '@open-draft/deferred-promise'
import { invariant } from 'outvariant'
import { until } from '@open-draft/until'
import { HttpRequestEventMap, IS_PATCHED_MODULE } from '../../glossary'
Expand Down Expand Up @@ -46,13 +47,21 @@ export class FetchInterceptor extends Interceptor<HttpRequestEventMap> {

this.logger.info('awaiting for the mocked response...')

const signal = interactiveRequest.signal
kettanaito marked this conversation as resolved.
Show resolved Hide resolved
const requestAbortRejection = new DeferredPromise<string>()

signal.addEventListener('abort', () => requestAbortRejection.reject())
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should we forward the abort information exposed to this listener, like abort reason and such? It does work without it so I assume the abort controller already exposes that information in the abort error, is that correct?

As in, why this is not needed?

signal.addEventListener('abort', () => {
  requestAbortRejection.reject(signal.reason)
})

🤔

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It turns out it does not work.
The reason your test passes is because you abort the request before it starts. If you try the same thing with a pending request, abortError will be undefined.

If the request is aborted, the condition line 73 is not fulfilled, the flow will therefore continue and execute the native request, which will throw because it has been aborted. This is why it looks like it works.

Please also note that the condition line 73 is incorrect : if null is given as a reason, the condition will fails and the flow will continue. While this do not lead to a runtime issue as explained above, I changed the condition to also check if the abortion promise was rejected.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I understand how it affects the promise flow, us using the abort reason as the rejection value and that it may produce false negatives, but my question was about whether we have to respect that reason in any way? As in, forward it directly. We can always reject with an object, or a different data structure to prevent false positives.


const resolverResult = await until(async () => {
await this.emitter.untilIdle(
const allListenerResolved = this.emitter.untilIdle(
'request',
({ args: [{ requestId: pendingRequestId }] }) => {
return pendingRequestId === requestId
}
)

await Promise.race([requestAbortRejection, allListenerResolved])

this.logger.info('all request listeners have been resolved!')

const [mockedResponse] = await interactiveRequest.respondWith.invoked()
Expand All @@ -62,10 +71,7 @@ export class FetchInterceptor extends Interceptor<HttpRequestEventMap> {
})

if (resolverResult.error) {
const error = Object.assign(new TypeError('Failed to fetch'), {
cause: resolverResult.error,
})
return Promise.reject(error)
return Promise.reject(resolverResult.error)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I believe this is incorrect. I copied the previous behavior from Undici and we must comply by it. Note that the FetchInterceptor is primarily meant for Node, and I trust Undici implement the spec rather faithfully.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'd suggest we revert this particular change for now because it's not related to the abort controller support. We can discuss it as a separate improvement point, what do you think?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I checked the Undici implementation and there are only two causes of error : abortion and network issue.
Since the abortion error is well defined (specific class and specific error code), we can check the error type and reject accordingly.
If we don't do that, we deviate from production behavior.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I agree, we should do it the same way: handle the two error scenarios separately:

  • Keep what you've introduced for abort errors.
  • Revert what was there previously (the TypeError) to handle all the other errors (effectively, network errors).

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is what I've done in my latest commit ;)

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks so much for addressing it so quickly! Will give it the last round of review and let's get this published.

}

const mockedResponse = resolverResult.data
Expand Down
100 changes: 100 additions & 0 deletions test/modules/fetch/compliance/abort-conrtoller.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
// @vitest-environment node
import { afterAll, beforeAll, expect, it } from 'vitest'
import { DeferredPromise } from '@open-draft/deferred-promise'
import { HttpServer } from '@open-draft/test-server/http'
import { FetchInterceptor } from '../../../../src/interceptors/fetch'
import { sleep } from '../../../helpers'

const httpServer = new HttpServer((app) => {
app.get('/', (_req, res) => {
res.status(200).send('/')
})
app.get('/get', (_req, res) => {
res.status(200).send('/get')
})
})

const interceptor = new FetchInterceptor()

beforeAll(async () => {
// interceptor.apply()
await httpServer.listen()
})

afterAll(async () => {
// interceptor.dispose()
await httpServer.close()
})

it('aborts unsent request when the original request is aborted', async () => {
interceptor.on('request', () => {
expect.fail('must not sent the request')
})

const controller = new AbortController()
const request = fetch(httpServer.http.url('/'), {
signal: controller.signal,
})

const requestAborted = new DeferredPromise<NodeJS.ErrnoException>()
request.catch(requestAborted.resolve)

controller.abort()

const abortError = await requestAborted
console.log({ abortError })

expect(abortError.name).toBe('AbortError')
expect(abortError.code).toBe(20)
expect(abortError.message).toBe('This operation was aborted')
})

it('forwards custom abort reason to the aborted request', async () => {
interceptor.on('request', () => {
expect.fail('must not sent the request')
})

const controller = new AbortController()
const request = fetch(httpServer.http.url('/'), {
signal: controller.signal,
})

const requestAborted = new DeferredPromise<NodeJS.ErrnoException>()
request.catch(requestAborted.resolve)

controller.abort(new Error('Custom abort reason'))

const abortError = await requestAborted
console.log({ abortError })

expect(abortError.name).toBe('Error')
expect(abortError.code).toBeUndefined()
expect(abortError.message).toBe('Custom abort reason')
})

it('aborts a pending request when the original request is aborted', async () => {
const requestListenerCalled = new DeferredPromise<void>()
const requestAborted = new DeferredPromise<Error>()

interceptor.on('request', async ({ request }) => {
requestListenerCalled.resolve()
await sleep(1_000)
request.respondWith(new Response())
})

const controller = new AbortController()
const request = fetch(httpServer.http.url('/'), {
signal: controller.signal,
}).then(() => {
expect.fail('must not return any response')
})

request.catch(requestAborted.resolve)
await requestListenerCalled

controller.abort()

const abortError = await requestAborted
expect(abortError.name).toBe('AbortError')
expect(abortError.message).toEqual('This operation was aborted')
})
Loading