-
-
Notifications
You must be signed in to change notification settings - Fork 156
fix(fetch): respect "abort" event on the request signal #394
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
Merged
Merged
Changes from all commits
Commits
Show all changes
15 commits
Select commit
Hold shift + click to select a range
52aa901
fix: abort request if the user aborts it
JesusTheHun d48c61a
fix: reject user request with native error instead of wrapper error
JesusTheHun 8e229ca
docs: fix request typo in readme (#404)
96e1685
chore: migrate to pnpm (#407)
kettanaito 94a2a59
fix: set "X-Request-Id" header in XMLHttpRequest only in Node.js (#397)
avivasyuta e0ca09d
Merge branch 'main' into fix/honor-abort-signals
kettanaito 864a06e
test: move fetch abort controller compliance test
kettanaito faff151
fix: forward abort reason
JesusTheHun 4753f13
fix: split request rejection logic
JesusTheHun 46dd281
chore(fetch): reject request with request abort rejection reason
kettanaito e5818a1
Merge branch 'main' into fix/honor-abort-signals
kettanaito f57fcf9
Merge branch 'main' into fix/honor-abort-signals
kettanaito b5e4db9
fix: listen to "abort" event once
kettanaito 5470be2
chore: remove log from test
kettanaito 25ad663
Merge branch 'main' into fix/honor-abort-signals
kettanaito File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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' | ||
|
|
@@ -46,13 +47,27 @@ export class FetchInterceptor extends Interceptor<HttpRequestEventMap> { | |
|
|
||
| this.logger.info('awaiting for the mocked response...') | ||
|
|
||
| const signal = interactiveRequest.signal | ||
| const requestAborted = new DeferredPromise() | ||
|
|
||
| signal.addEventListener( | ||
| 'abort', | ||
| () => { | ||
| requestAborted.reject(signal.reason) | ||
| }, | ||
| { once: true } | ||
|
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I've made sure we only react to the abort event once to make sure there's no event emitter memory leak when cloning requests (each request clone will also preserve previously attached listeners, I believe; I recall an issue about this in the past). |
||
| ) | ||
|
|
||
| const resolverResult = await until(async () => { | ||
| await this.emitter.untilIdle( | ||
| const allListenersResolved = this.emitter.untilIdle( | ||
| 'request', | ||
| ({ args: [{ requestId: pendingRequestId }] }) => { | ||
| return pendingRequestId === requestId | ||
| } | ||
| ) | ||
|
|
||
| await Promise.race([requestAborted, allListenersResolved]) | ||
|
|
||
| this.logger.info('all request listeners have been resolved!') | ||
|
|
||
| const [mockedResponse] = await interactiveRequest.respondWith.invoked() | ||
|
|
@@ -61,10 +76,15 @@ export class FetchInterceptor extends Interceptor<HttpRequestEventMap> { | |
| return mockedResponse | ||
| }) | ||
|
|
||
| if (requestAborted.state === 'rejected') { | ||
| return Promise.reject(requestAborted.rejectionReason) | ||
| } | ||
|
|
||
| if (resolverResult.error) { | ||
| const error = Object.assign(new TypeError('Failed to fetch'), { | ||
| cause: resolverResult.error, | ||
| }) | ||
|
|
||
| return Promise.reject(error) | ||
| } | ||
|
|
||
|
|
||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,131 @@ | ||
| // @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') | ||
| }) | ||
| app.get('/delayed', (_req, res) => { | ||
| setTimeout(() => { | ||
| res.status(200).send('/delayed') | ||
| }, 1000) | ||
| }) | ||
| }) | ||
|
|
||
| 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 | ||
|
|
||
| expect(abortError.name).toBe('AbortError') | ||
| expect(abortError.code).toBe(20) | ||
| expect(abortError.message).toBe('This operation was aborted') | ||
| }) | ||
|
|
||
| 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') | ||
| }) | ||
|
|
||
| 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('forwards custom abort reason to the request if pending', 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(new Error('Custom abort reason')) | ||
|
|
||
| const abortError = await requestAborted | ||
| expect(abortError.name).toBe('Error') | ||
| expect(abortError.message).toEqual('Custom abort reason') | ||
| }) |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.