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 1 commit
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
9 changes: 8 additions & 1 deletion src/interceptors/fetch/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -70,10 +70,17 @@ export class FetchInterceptor extends Interceptor<HttpRequestEventMap> {
return mockedResponse
})

if (resolverResult.error || requestAbortRejection.state === 'rejected') {
if (requestAbortRejection.state === 'rejected') {
Copy link
Member

@kettanaito kettanaito Aug 30, 2023

Choose a reason for hiding this comment

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

Do you think we should conceptually treat this promise as resolved instead?

If we imagine promise as an intention, then the intention here is to know when the request has been aborted by another actor. In that light, an aborted request would mean a resolved requestAborted promise.

It would make this check read much nicer as well. What are your thoughts on this?

I'm also a bit hesitant to base this condition on the request abort promise itself. I'd rather we used that promise in the Promise.race() but handled the resolverResult.error differently. This implies that requestAbortRejection can still throw but it does so with a custom error/object that is later checked on the resolverResult.error:

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

if (resolverResult.error) {
  if (resolverResult.error.type === 'aborted') {
    return Promise.reject(resolverResult.error.reason)
  }

  return /* create the TypeError, set "cause" */
}

We can also use a custom AbortError class to prevent any false positives here since it's possible for the user to abort a request with a compatible object as the 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 is true that the promise encapsulate the expectation of an aborted request.
Resolving it would mean that the expectation has been reached, which is logically correct.
However, in our case, we use a promise as a poor man's event : the promise rejection carries no expectation and therefore no logical meaning. We just want to be notified when the abortion happens.
From there, this promise is a mere async tool.
Resolving it, then check the race winner, then throw a custom object, check the resolverResult resolution value, all of that to ultimately throw the error we had in the first place, seems unnecessary to me.
On a side note, in the end, I'm not the maintainer of the project, if you feel more comfortable with this extra layer, do it, this is your call :)

Copy link
Member

Choose a reason for hiding this comment

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

Thanks for your input. I agree that it's mainly a semantic difference. We can leave it rejecting as-is. On the second half, I will lean toward making the resolver handling more streamlined, handling it by what the until returns instead of relying on external factors like the rejection promise. I will push the change shortly.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Actually my point is that this is not a semantic difference but a technical one. We expect something to happen, using resolve or reject make no difference. If our expectation could fail then it would make a semantic difference.

Copy link
Member

Choose a reason for hiding this comment

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

I ended up leaving the explicit rejection promise check but instead of coupling the request rejection promise and the resolver error, I reject the request promise with the abort rejection reason. Also, that is hell of a sentence to write.

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.

}

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

const mockedResponse = resolverResult.data

if (mockedResponse && !request.signal?.aborted) {
Expand Down
33 changes: 31 additions & 2 deletions test/modules/fetch/compliance/abort-conrtoller.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,35 @@ it('aborts unsent request when the original request is aborted', async () => {
expect(abortError.message).toBe('This operation was aborted')
})

it('forwards custom abort reason to the aborted request', async () => {

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('/delayed'), {
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).toBe('This operation was aborted')
})

it('forwards custom abort reason to the request if aborted before it starts', async () => {
interceptor.on('request', () => {
expect.fail('must not sent the request')
})
Expand All @@ -77,7 +105,8 @@ it('forwards custom abort reason to the aborted request', async () => {
expect(abortError.message).toBe('Custom abort reason')
})

it('aborts a pending request when the original request is aborted', async () => {

it('forwards custom abort reason to the request if pending', async () => {
const requestListenerCalled = new DeferredPromise<void>()
const requestAborted = new DeferredPromise<Error>()

Expand Down