Skip to content

Commit

Permalink
web runtime: add AbortController & AbortSignal (#32089)
Browse files Browse the repository at this point in the history
It adds AbortController and AbortSignal Web runtimes APIs to be used by the user at Edge Functions.

For doing that it delegates into `abort-controller` dependency that has been frozen to prevent any modification.

Co-authored-by: Zhang Zhi <20026577+fytriht@users.noreply.github.com>
  • Loading branch information
Kikobeats and fytriht authored Dec 21, 2021
1 parent f47a251 commit 0eba5b2
Show file tree
Hide file tree
Showing 9 changed files with 81 additions and 4 deletions.
4 changes: 0 additions & 4 deletions docs/api-reference/edge-runtime.md
Original file line number Diff line number Diff line change
Expand Up @@ -82,10 +82,6 @@ The following JavaScript language features are disabled, and **will not work:**
- [`eval`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval): Evaluates JavaScript code represented as a string
- [`new Function(evalString)`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function): Creates a new function with the code provided as an argument

The following Web APIs are currently not supported, but will be in the future:

- [`AbortController`](https://developer.mozilla.org/en-US/docs/Web/API/AbortController): Abort one or more Web requests when desired

## Related

<div class="card">
Expand Down
21 changes: 21 additions & 0 deletions packages/next/compiled/abort-controller/LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2017 Toru Nagashima

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions packages/next/compiled/abort-controller/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
{"name":"abort-controller","main":"abort-controller.js","author":"Toru Nagashima (https://github.com/mysticatea)","license":"MIT"}
6 changes: 6 additions & 0 deletions packages/next/server/web/sandbox/context.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,10 @@ import { requireDependencies } from './require'
import { TransformStream } from 'next/dist/compiled/web-streams-polyfill'
import cookie from 'next/dist/compiled/cookie'
import * as polyfills from './polyfills'
import {
AbortController,
AbortSignal,
} from 'next/dist/compiled/abort-controller'
import vm from 'vm'

const WEBPACK_HASH_REGEX =
Expand Down Expand Up @@ -185,6 +189,8 @@ function createContext() {
timeLog: console.timeLog.bind(console),
warn: console.warn.bind(console),
},
AbortController: AbortController,
AbortSignal: AbortSignal,
CryptoKey: polyfills.CryptoKey,
Crypto: polyfills.Crypto,
crypto: new polyfills.Crypto(),
Expand Down
11 changes: 11 additions & 0 deletions packages/next/taskfile.js
Original file line number Diff line number Diff line change
Expand Up @@ -1331,6 +1331,16 @@ export async function ncc_web_streams_polyfill(task, opts) {
.target('compiled/web-streams-polyfill')
}
// eslint-disable-next-line camelcase
externals['abort-controller'] = 'next/dist/compiled/abort-controller'
export async function ncc_abort_controller(task, opts) {
await task
.source(
opts.src || relative(__dirname, require.resolve('abort-controller'))
)
.ncc({ packageName: 'abort-controller', externals })
.target('compiled/abort-controller')
}
// eslint-disable-next-line camelcase
externals['formdata-node'] = 'next/dist/compiled/formdata-node'
export async function ncc_formdata_node(task, opts) {
await task
Expand Down Expand Up @@ -1540,6 +1550,7 @@ export async function ncc(task, opts) {
'ncc_uuid',
'ncc_formdata_node',
'ncc_web_streams_polyfill',
'ncc_abort_controller',
'ncc_minimatch',
'ncc_mini_css_extract_plugin',
],
Expand Down
6 changes: 6 additions & 0 deletions packages/next/types/misc.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -244,6 +244,12 @@ declare module 'next/dist/compiled/web-streams-polyfill' {
import m from 'web-streams-polyfill/ponyfill'
export = m
}
declare module 'next/dist/compiled/abort-controller' {
type BaseAbortController = typeof AbortController
type BaseAbortSignal = typeof AbortSignal
export { BaseAbortController as AbortController }
export { BaseAbortSignal as AbortSignal }
}
declare module 'next/dist/compiled/ua-parser-js' {
import m from 'ua-parser-js'
export = m
Expand Down
23 changes: 23 additions & 0 deletions test/integration/middleware/core/pages/interface/_middleware.js
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,29 @@ export async function middleware(request) {
return fetch(url)
}

if (url.pathname.endsWith('/abort-controller')) {
const controller = new AbortController()
const signal = controller.signal

controller.abort()
const response = {}

try {
await fetch('https://example.com', { signal })
} catch (err) {
response.error = {
name: err.name,
message: err.message,
}
} finally {
return new NextResponse(JSON.stringify(response), {
headers: {
'content-type': 'application/json; charset=utf-8',
},
})
}
}

if (url.pathname.endsWith('/dynamic-replace')) {
return NextResponse.rewrite('/_interface/dynamic-path')
}
Expand Down
12 changes: 12 additions & 0 deletions test/integration/middleware/core/test/index.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -405,6 +405,18 @@ function interfaceTests(locale = '') {
expect(response.error.name).not.toBe('TypeError')
})

it(`${locale} abort a fetch request`, async () => {
const res = await fetchViaHTTP(
context.appPort,
'/interface/abort-controller'
)
const response = await res.json()

expect('error' in response).toBe(true)
expect(response.error.name).toBe('AbortError')
expect(response.error.message).toBe('The user aborted a request.')
})

it(`${locale} should validate request url parameters from a static route`, async () => {
const res = await fetchViaHTTP(
context.appPort,
Expand Down

0 comments on commit 0eba5b2

Please sign in to comment.