Unverified Commit fcfbceaa authored by Jan Potoms's avatar Jan Potoms Committed by GitHub

Fix cancellation control flow (#15361)

parent ef637b38
...@@ -22,10 +22,14 @@ import { ...@@ -22,10 +22,14 @@ import {
normalizePathTrailingSlash, normalizePathTrailingSlash,
} from '../../../client/normalize-trailing-slash' } from '../../../client/normalize-trailing-slash'
const ABORTED = Symbol('aborted')
const basePath = (process.env.__NEXT_ROUTER_BASEPATH as string) || '' const basePath = (process.env.__NEXT_ROUTER_BASEPATH as string) || ''
function buildCancellationError() {
return Object.assign(new Error('Route Cancelled'), {
cancelled: true,
})
}
export function addBasePath(path: string): string { export function addBasePath(path: string): string {
return basePath return basePath
? path === '/' ? path === '/'
...@@ -525,21 +529,16 @@ export default class Router implements BaseRouter { ...@@ -525,21 +529,16 @@ export default class Router implements BaseRouter {
Router.events.emit('routeChangeStart', as) Router.events.emit('routeChangeStart', as)
// If shallow is true and the route exists in the router cache we reuse the previous result try {
return this.getRouteInfo(route, pathname, query, as, shallow).then( const routeInfo = await this.getRouteInfo(
(routeInfo) => { route,
pathname,
query,
as,
shallow
)
const { error } = routeInfo const { error } = routeInfo
if (error && error.cancelled) {
// An event already has been fired
return false
}
if (error && error[ABORTED]) {
Router.events.emit('routeChangeError', error, as)
return false
}
Router.events.emit('beforeHistoryChange', as) Router.events.emit('beforeHistoryChange', as)
this.changeState(method, url, as, options) this.changeState(method, url, as, options)
...@@ -550,8 +549,8 @@ export default class Router implements BaseRouter { ...@@ -550,8 +549,8 @@ export default class Router implements BaseRouter {
!(routeInfo.Component as any).getInitialProps !(routeInfo.Component as any).getInitialProps
} }
return this.set(route, pathname!, query, cleanedAs, routeInfo).then( await this.set(route, pathname!, query, cleanedAs, routeInfo)
() => {
if (error) { if (error) {
Router.events.emit('routeChangeError', error, cleanedAs) Router.events.emit('routeChangeError', error, cleanedAs)
throw error throw error
...@@ -565,10 +564,12 @@ export default class Router implements BaseRouter { ...@@ -565,10 +564,12 @@ export default class Router implements BaseRouter {
Router.events.emit('routeChangeComplete', as) Router.events.emit('routeChangeComplete', as)
return true return true
} catch (err) {
if (err.cancelled) {
return false
} }
) throw err
} }
)
} }
changeState( changeState(
...@@ -605,27 +606,21 @@ export default class Router implements BaseRouter { ...@@ -605,27 +606,21 @@ export default class Router implements BaseRouter {
} }
} }
getRouteInfo( async handleRouteInfoError(
route: string, err: Error & { code: any; cancelled: boolean },
pathname: string, pathname: string,
query: any, query: any,
as: string, as: string,
shallow: boolean = false loadErrorFail?: boolean
): Promise<RouteInfo> { ): Promise<RouteInfo> {
const cachedRouteInfo = this.components[route] if (err.cancelled) {
// bubble up cancellation errors
// If there is a shallow route transition possible throw err
// If the route is already rendered on the screen.
if (shallow && cachedRouteInfo && this.route === route) {
return Promise.resolve(cachedRouteInfo)
} }
const handleError = (
err: Error & { code: any; cancelled: boolean; [ABORTED]: boolean },
loadErrorFail?: boolean
) => {
return new Promise((resolve) => {
if (err.code === 'PAGE_LOAD_ERROR' || loadErrorFail) { if (err.code === 'PAGE_LOAD_ERROR' || loadErrorFail) {
Router.events.emit('routeChangeError', err, as)
// If we can't load the page it could be one of following reasons // If we can't load the page it could be one of following reasons
// 1. Page doesn't exists // 1. Page doesn't exists
// 2. Page does exist in a different zone // 2. Page does exist in a different zone
...@@ -635,66 +630,56 @@ export default class Router implements BaseRouter { ...@@ -635,66 +630,56 @@ export default class Router implements BaseRouter {
window.location.href = as window.location.href = as
// Changing the URL doesn't block executing the current code path. // Changing the URL doesn't block executing the current code path.
// So, we need to mark it as aborted and stop the routing logic. // So let's throw a cancellation error stop the routing logic.
err[ABORTED] = true throw buildCancellationError()
// @ts-ignore TODO: fix the control flow here
return resolve({ error: err })
} }
if (err.cancelled) { try {
// @ts-ignore TODO: fix the control flow here const { page: Component } = await this.fetchComponent('/_error')
return resolve({ error: err }) const routeInfo: RouteInfo = { Component, err, error: err }
}
resolve( try {
this.fetchComponent('/_error') routeInfo.props = await this.getInitialProps(Component, {
.then((res) => {
const { page: Component } = res
const routeInfo: RouteInfo = { Component, err }
return new Promise((resolveRouteInfo) => {
this.getInitialProps(Component, {
err, err,
pathname, pathname,
query, query,
} as any).then( } as any)
(props) => { } catch (gipErr) {
routeInfo.props = props console.error('Error in error page `getInitialProps`: ', gipErr)
routeInfo.error = err
resolveRouteInfo(routeInfo)
},
(gipErr) => {
console.error(
'Error in error page `getInitialProps`: ',
gipErr
)
routeInfo.error = err
routeInfo.props = {} routeInfo.props = {}
resolveRouteInfo(routeInfo)
} }
)
}) as Promise<RouteInfo> return routeInfo
}) } catch (routeInfoErr) {
.catch((routeInfoErr) => handleError(routeInfoErr, true)) return this.handleRouteInfoError(routeInfoErr, pathname, query, as, true)
) }
}) as Promise<RouteInfo>
} }
return (new Promise((resolve, reject) => { async getRouteInfo(
if (cachedRouteInfo) { route: string,
return resolve(cachedRouteInfo) pathname: string,
query: any,
as: string,
shallow: boolean = false
): Promise<RouteInfo> {
try {
const cachedRouteInfo = this.components[route]
if (shallow && cachedRouteInfo && this.route === route) {
return cachedRouteInfo
} }
this.fetchComponent(route).then( const routeInfo = cachedRouteInfo
? cachedRouteInfo
: await this.fetchComponent(route).then(
(res) => (res) =>
resolve({ ({
Component: res.page, Component: res.page,
__N_SSG: res.mod.__N_SSG, __N_SSG: res.mod.__N_SSG,
__N_SSP: res.mod.__N_SSP, __N_SSP: res.mod.__N_SSP,
}), } as RouteInfo)
reject
) )
}) as Promise<RouteInfo>)
.then((routeInfo: RouteInfo) => {
const { Component, __N_SSG, __N_SSP } = routeInfo const { Component, __N_SSG, __N_SSP } = routeInfo
if (process.env.NODE_ENV !== 'production') { if (process.env.NODE_ENV !== 'production') {
...@@ -716,7 +701,7 @@ export default class Router implements BaseRouter { ...@@ -716,7 +701,7 @@ export default class Router implements BaseRouter {
) )
} }
return this._getData<RouteInfo>(() => const props = await this._getData<RouteInfo>(() =>
__N_SSG __N_SSG
? this._getStaticData(dataHref!) ? this._getStaticData(dataHref!)
: __N_SSP : __N_SSP
...@@ -730,13 +715,13 @@ export default class Router implements BaseRouter { ...@@ -730,13 +715,13 @@ export default class Router implements BaseRouter {
asPath: as, asPath: as,
} as any } as any
) )
).then((props) => { )
routeInfo.props = props routeInfo.props = props
this.components[route] = routeInfo this.components[route] = routeInfo
return routeInfo return routeInfo
}) } catch (err) {
}) return this.handleRouteInfoError(err, pathname, query, as)
.catch(handleError) }
} }
set( set(
...@@ -917,9 +902,7 @@ export default class Router implements BaseRouter { ...@@ -917,9 +902,7 @@ export default class Router implements BaseRouter {
abortComponentLoad(as: string): void { abortComponentLoad(as: string): void {
if (this.clc) { if (this.clc) {
const e = new Error('Route Cancelled') Router.events.emit('routeChangeError', buildCancellationError(), as)
;(e as any).cancelled = true
Router.events.emit('routeChangeError', e, as)
this.clc() this.clc()
this.clc = null this.clc = null
} }
......
...@@ -104,7 +104,7 @@ describe('Build Output', () => { ...@@ -104,7 +104,7 @@ describe('Build Output', () => {
expect(parseFloat(err404FirstLoad) - 63).toBeLessThanOrEqual(0) expect(parseFloat(err404FirstLoad) - 63).toBeLessThanOrEqual(0)
expect(err404FirstLoad.endsWith('kB')).toBe(true) expect(err404FirstLoad.endsWith('kB')).toBe(true)
expect(parseFloat(sharedByAll) - 59).toBeLessThanOrEqual(0) expect(parseFloat(sharedByAll) - 59.2).toBeLessThanOrEqual(0)
expect(sharedByAll.endsWith('kB')).toBe(true) expect(sharedByAll.endsWith('kB')).toBe(true)
if (_appSize.endsWith('kB')) { if (_appSize.endsWith('kB')) {
......
...@@ -80,7 +80,7 @@ describe('Production response size', () => { ...@@ -80,7 +80,7 @@ describe('Production response size', () => {
) )
// These numbers are without gzip compression! // These numbers are without gzip compression!
const delta = responseSizesBytes - 273 * 1024 const delta = responseSizesBytes - 274 * 1024
expect(delta).toBeLessThanOrEqual(1024) // don't increase size more than 1kb expect(delta).toBeLessThanOrEqual(1024) // don't increase size more than 1kb
expect(delta).toBeGreaterThanOrEqual(-1024) // don't decrease size more than 1kb without updating target expect(delta).toBeGreaterThanOrEqual(-1024) // don't decrease size more than 1kb without updating target
}) })
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment