Unverified Commit 3c44a5d7 authored by Marcos Hernanz's avatar Marcos Hernanz Committed by GitHub

fix(hmr): only reconnect a closed WebSocket on visibilitychange/online

The visibilitychange/online handlers added in #91416 replace the HMR
WebSocket whenever it is not OPEN. A socket that is still CONNECTING
was replaced too, which closes it and fires its disconnect handler; that
handler schedules another reconnect one second later, which closes the
new socket, and so on indefinitely.

Chrome activates prerendered pages (Speculation Rules, omnibox
preloading) while the deferred WebSocket handshake is still pending, so
every prerendered dev page hit this. If the first socket had already
reached the server it also consumed the React debug channel for the
request, and the page never hydrated.

Only reconnect when the socket is CLOSED. By then the disconnect handler
has already run and only a retry timer is pending, so the sleep/wake
reconnect keeps working.

Fixes #98212
parent 65c832c8
...@@ -142,10 +142,15 @@ export function createWebSocket( ...@@ -142,10 +142,15 @@ export function createWebSocket(
return newWebSocket return newWebSocket
} }
// Reconnect when the page becomes visible or the browser comes back online
// (e.g. after sleep/wake) and the socket is CLOSED. A socket that is still
// CONNECTING must be left alone: closing it would fire its disconnect
// handler, which schedules a reconnect that closes the new socket, and so on
// (e.g. when a prerendered page is activated while the handshake is pending).
function handleVisibilityChange() { function handleVisibilityChange() {
if ( if (
document.visibilityState === 'visible' && document.visibilityState === 'visible' &&
webSocket.readyState !== WebSocket.OPEN webSocket.readyState === WebSocket.CLOSED
) { ) {
reconnections = 0 reconnections = 0
clearTimeout(timer) clearTimeout(timer)
...@@ -154,7 +159,7 @@ export function createWebSocket( ...@@ -154,7 +159,7 @@ export function createWebSocket(
} }
function handleOnlineEvent() { function handleOnlineEvent() {
if (webSocket.readyState !== WebSocket.OPEN) { if (webSocket.readyState === WebSocket.CLOSED) {
reconnections = 0 reconnections = 0
clearTimeout(timer) clearTimeout(timer)
init() init()
......
...@@ -95,10 +95,15 @@ export function connectHMR(options: { path: string; assetPrefix: string }) { ...@@ -95,10 +95,15 @@ export function connectHMR(options: { path: string; assetPrefix: string }) {
source.onmessage = handleMessage source.onmessage = handleMessage
} }
// Reconnect when the page becomes visible or the browser comes back online
// (e.g. after sleep/wake) and the socket is CLOSED. A socket that is still
// CONNECTING must be left alone: closing it would fire its disconnect
// handler, which schedules a reconnect that closes the new socket, and so on
// (e.g. when a prerendered page is activated while the handshake is pending).
function handleVisibilityChange() { function handleVisibilityChange() {
if ( if (
document.visibilityState === 'visible' && document.visibilityState === 'visible' &&
source.readyState !== WebSocket.OPEN source.readyState === WebSocket.CLOSED
) { ) {
reconnections = 0 reconnections = 0
clearTimeout(timer) clearTimeout(timer)
...@@ -107,7 +112,7 @@ export function connectHMR(options: { path: string; assetPrefix: string }) { ...@@ -107,7 +112,7 @@ export function connectHMR(options: { path: string; assetPrefix: string }) {
} }
function handleOnlineEvent() { function handleOnlineEvent() {
if (source.readyState !== WebSocket.OPEN) { if (source.readyState === WebSocket.CLOSED) {
reconnections = 0 reconnections = 0
clearTimeout(timer) clearTimeout(timer)
init() init()
......
import { FileRef, nextTestSetup } from 'e2e-utils'
import { retry, waitFor } from 'next-test-utils'
import path from 'path'
describe('app-dir HMR WebSocket reconnect', () => {
const { next } = nextTestSetup({
files: new FileRef(path.join(__dirname, 'fixtures', 'default-template')),
})
it('should not replace the socket when the page becomes visible while it is connecting', async () => {
let hmrSocketCount = 0
const browser = await next.browser('/', {
async beforePageLoad(page) {
page.on('websocket', (webSocket) => {
if (webSocket.url().includes('/_next/hmr')) {
hmrSocketCount++
}
})
// Fire `visibilitychange` while the HMR WebSocket is still connecting,
// as happens when a prerendered page is activated.
await page.addInitScript(`(() => {
const OriginalWebSocket = window.WebSocket
let fired = false
window.WebSocket = class extends OriginalWebSocket {
constructor(...args) {
super(...args)
if (!fired && String(args[0]).includes('/_next/hmr')) {
fired = true
queueMicrotask(() => {
document.dispatchEvent(new Event('visibilitychange'))
})
}
}
}
})()`)
},
})
await retry(async () => {
expect(await browser.log()).toContainEqual({
source: 'log',
message: '[HMR] connected',
})
})
// A faulty client would replace the socket right away, and again after the
// one second reconnect delay.
await waitFor(2000)
expect(hmrSocketCount).toBe(1)
})
})
...@@ -105,4 +105,45 @@ export function runBasicHmrTest(nextConfig: { ...@@ -105,4 +105,45 @@ export function runBasicHmrTest(nextConfig: {
await reloadPromise await reloadPromise
}) })
it('should not replace the HMR socket when the page becomes visible while it is connecting', async () => {
let hmrSocketCount = 0
const browser = await next.browser(basePath + '/hmr/about', {
async beforePageLoad(page) {
page.on('websocket', (webSocket) => {
if (webSocket.url().includes('/_next/hmr')) {
hmrSocketCount++
}
})
// Fire `visibilitychange` while the HMR WebSocket is still connecting,
// as happens when a prerendered page is activated.
await page.addInitScript(`(() => {
const OriginalWebSocket = window.WebSocket
let fired = false
window.WebSocket = class extends OriginalWebSocket {
constructor(...args) {
super(...args)
if (!fired && String(args[0]).includes('/_next/hmr')) {
fired = true
queueMicrotask(() => {
document.dispatchEvent(new Event('visibilitychange'))
})
}
}
}
})()`)
},
})
await retry(async () => {
expect(await browser.log()).toContainEqual({
source: 'log',
message: '[HMR] connected',
})
})
// A faulty client would replace the socket right away, and again after the
// one second reconnect delay.
await waitFor(2000)
expect(hmrSocketCount).toBe(1)
})
} }
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