Skip to content

Commit

Permalink
Remove pong HMR event as it is not used (vercel#54965)
Browse files Browse the repository at this point in the history
While investigating the HMR event types I noticed `pong` is not being used in Pages Router nor in App Router.

This PR removes the code that sends it as it's essentially dead code.
  • Loading branch information
timneutkens authored Sep 4, 2023
1 parent 7a1924e commit f313235
Show file tree
Hide file tree
Showing 8 changed files with 20 additions and 112 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -44,9 +44,6 @@ interface Dispatcher {
onRefresh(): void
}

// TODO-APP: add actual type
type PongEvent = any

let mostRecentCompilationHash: any = null
let __nextDevClientId = Math.round(Math.random() * 100 + Date.now())

Expand Down Expand Up @@ -408,9 +405,6 @@ function processMessage(
}
return
}
case 'pong': {
return
}
case 'devPagesManifestUpdate': {
return
}
Expand Down Expand Up @@ -481,7 +475,7 @@ export default function HotReload({
const router = useRouter()

useEffect(() => {
const handler = (event: MessageEvent<PongEvent>) => {
const handler = (event: MessageEvent<any>) => {
try {
processMessage(event, sendMessage, router, dispatcher)
} catch (err: any) {
Expand Down
14 changes: 0 additions & 14 deletions packages/next/src/server/dev/hot-reloader-types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@ export const enum HMR_ACTIONS_SENT_TO_BROWSER {
SERVER_ONLY_CHANGES = 'serverOnlyChanges',
BUILT = 'built',
BUILDING = 'building',
PONG = 'pong',
DEV_PAGES_MANIFEST_UPDATE = 'devPagesManifestUpdate',
TURBOPACK_MESSAGE = 'turbopack-message',
SERVER_ERROR = 'serverError',
Expand Down Expand Up @@ -69,16 +68,6 @@ interface ServerOnlyChangesAction {
pages: ReadonlyArray<string>
}

interface PongActionAppRouter {
action: HMR_ACTIONS_SENT_TO_BROWSER.PONG
success: boolean
}

interface PongActionPagesRouter {
event: HMR_ACTIONS_SENT_TO_BROWSER.PONG
success: boolean
}

interface DevPagesManifestUpdateAction {
action: HMR_ACTIONS_SENT_TO_BROWSER.DEV_PAGES_MANIFEST_UPDATE
data: [
Expand All @@ -88,11 +77,8 @@ interface DevPagesManifestUpdateAction {
]
}

type PongAction = PongActionAppRouter | PongActionPagesRouter

export type HMR_ACTION_TYPES =
| TurboPackMessageAction
| PongAction
| BuildingAction
| BuiltAction
| AddedPageAction
Expand Down
31 changes: 9 additions & 22 deletions packages/next/src/server/dev/on-demand-entry-handler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -615,11 +615,8 @@ export function onDemandEntryHandler({
disposeInactiveEntries(curEntries, maxInactiveAge)
}, pingIntervalTime + 1000).unref()

function handleAppDirPing(
tree: FlightRouterState
): { success: true } | { invalid: true } {
function handleAppDirPing(tree: FlightRouterState): void {
const pages = getEntrypointsFromTree(tree, true)
let toSend: { invalid: true } | { success: true } = { invalid: true }

for (const page of pages) {
for (const compilerType of [
Expand Down Expand Up @@ -651,17 +648,12 @@ export function onDemandEntryHandler({
}
entryInfo.lastActiveTime = Date.now()
entryInfo.dispose = false
toSend = { success: true }
}
}

return toSend
}

function handlePing(pg: string) {
function handlePing(pg: string): void {
const page = normalizePathSep(pg)
let toSend: { invalid: true } | { success: true } = { invalid: true }

for (const compilerType of [
COMPILER_NAMES.client,
COMPILER_NAMES.server,
Expand All @@ -674,7 +666,7 @@ export function onDemandEntryHandler({
if (!entryInfo) {
// if (page !== lastEntry) client pings, but there's no entry for page
if (compilerType === COMPILER_NAMES.client) {
return { invalid: true }
return
}
continue
}
Expand All @@ -693,9 +685,8 @@ export function onDemandEntryHandler({
}
entryInfo.lastActiveTime = Date.now()
entryInfo.dispose = false
toSend = { success: true }
}
return toSend
return
}

async function ensurePageImpl({
Expand Down Expand Up @@ -963,15 +954,11 @@ export function onDemandEntryHandler({
)

if (parsedData.event === 'ping') {
const result = parsedData.appDirRoute
? handleAppDirPing(parsedData.tree)
: handlePing(parsedData.page)
client.send(
JSON.stringify({
...result,
[parsedData.appDirRoute ? 'action' : 'event']: 'pong',
})
)
if (parsedData.appDirRoute) {
handleAppDirPing(parsedData.tree)
} else {
handlePing(parsedData.page)
}
}
} catch {}
})
Expand Down
19 changes: 2 additions & 17 deletions packages/next/src/server/lib/router-utils/setup-dev.ts
Original file line number Diff line number Diff line change
Expand Up @@ -871,24 +871,9 @@ async function startWatcher(opts: SetupOpts) {

// Next.js messages
switch (parsedData.event) {
case 'ping': {
// const result = parsedData.appDirRoute
// ? handleAppDirPing(parsedData.tree)
// : handlePing(parsedData.page)
hotReloader.send(
parsedData.appDirRouter
? {
action: HMR_ACTIONS_SENT_TO_BROWSER.PONG,
success: true,
}
: {
event: HMR_ACTIONS_SENT_TO_BROWSER.PONG,
success: true,
}
)
case 'ping':
// Ping doesn't need additional handling in Turbopack.
break
}

case 'span-end':
case 'client-error': // { errorCount, clientId }
case 'client-warning': // { warningCount, clientId }
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
import { join } from 'path'
import webdriver from 'next-webdriver'
import { createNext, FileRef } from 'e2e-utils'
import { check, getRedboxHeader, hasRedbox, waitFor } from 'next-test-utils'
import { check, getRedboxHeader, hasRedbox } from 'next-test-utils'
import { NextInstance } from 'test/lib/next-modes/base'

const installCheckVisible = (browser) => {
Expand Down Expand Up @@ -319,10 +319,6 @@ describe('GS(S)P Server-Side Change Reloading', () => {
expect(props.count).toBe(1)
expect(props.data).toEqual({ hello: 'world' })

// wait longer than the max inactive age for on-demand entries
// to ensure we aren't incorrectly disposing the active entry
await waitFor(20 * 1000)

const page = 'lib/data.json'
const originalContent = await next.readFile(page)

Expand Down
3 changes: 2 additions & 1 deletion test/integration/dynamic-routing/test/index.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -130,7 +130,8 @@ function runTests({ dev }) {
}

if (dev) {
it('should not have error after pinging WebSocket', async () => {
// TODO: pong event not longer exist, refactor test.
it.skip('should not have error after pinging WebSocket', async () => {
const browser = await webdriver(appPort, '/')
await browser.eval(`(function() {
window.uncaughtErrs = []
Expand Down
43 changes: 2 additions & 41 deletions test/integration/ondemand/test/index.test.js
Original file line number Diff line number Diff line change
@@ -1,11 +1,9 @@
/* eslint-env jest */
import WebSocket from 'ws'
import { join } from 'path'
import webdriver from 'next-webdriver'
import getPort from 'get-port'
import {
renderViaHTTP,
fetchViaHTTP,
killApp,
waitFor,
check,
Expand All @@ -14,7 +12,6 @@ import {
getBuildManifest,
initNextServerScript,
} from 'next-test-utils'
import { assetPrefix } from '../next.config'

const appDir = join(__dirname, '../')
const context = {}
Expand All @@ -31,53 +28,20 @@ const startServer = async (optEnv = {}, opts) => {
context.server = await initNextServerScript(scriptPath, /ready on/i, env)
}

const doPing = (page) => {
return new Promise((resolve) => {
context.ws.onmessage = (e) => {
console.log(e)

resolve()
}
context.ws.send(JSON.stringify({ event: 'ping', page }))
})
}

describe('On Demand Entries', () => {
it('should pass', () => {})
beforeAll(async () => {
await startServer()

// Send an initial request to nextjs to establish an 'upgrade' listener
// If we send the websocket request as the first thing, it will result in 404 due to listener not set yet
// This is by design as the 'upgrade' listener is set during the first request run
await fetchViaHTTP(context.appPort, '/')

await new Promise((resolve, reject) => {
context.ws = new WebSocket(
`ws://localhost:${context.appPort}${
assetPrefix ? `/${assetPrefix}` : ''
}/_next/webpack-hmr`
)
context.ws.on('open', () => resolve())
context.ws.on('error', (err) => {
console.error(err)

context.ws.close()
reject()
})
})
})
afterAll(() => {
context.ws.close()
killApp(context.server)
})

it('should compile pages for SSR', async () => {
// The buffer of built page uses the on-demand-entries-ping to know which pages should be
// buffered. Therefore, we need to double each render call with a ping.
const pageContent = await renderViaHTTP(context.appPort, '/')
await doPing('/')
expect(pageContent.includes('Index Page')).toBeTruthy()
expect(pageContent.includes('Index Page')).toBeTrue()
})

it('should compile pages for JSON page requests', async () => {
Expand All @@ -87,19 +51,16 @@ describe('On Demand Entries', () => {
context.appPort,
join('/_next', pageFile)
)
expect(pageContent.includes('About Page')).toBeTruthy()
expect(pageContent.includes('About Page')).toBeTrue()
})

it('should dispose inactive pages', async () => {
await renderViaHTTP(context.appPort, '/')
await doPing('/')

// Render two pages after the index, since the server keeps at least two pages
await renderViaHTTP(context.appPort, '/about')
await doPing('/about')

await renderViaHTTP(context.appPort, '/third')
await doPing('/third')

// Wait maximum of jest.setTimeout checking
// for disposing /about
Expand Down
8 changes: 3 additions & 5 deletions test/lib/browsers/playwright.ts
Original file line number Diff line number Diff line change
Expand Up @@ -191,11 +191,9 @@ export class Playwright extends BrowserInterface {
websocketFrames.push({ payload: frame.payload })

if (tracePlaywright) {
if (!frame.payload.includes('pong')) {
page
.evaluate(`console.log('received ws message ${frame.payload}')`)
.catch(() => {})
}
page
.evaluate(`console.log('received ws message ${frame.payload}')`)
.catch(() => {})
}
})
})
Expand Down

0 comments on commit f313235

Please sign in to comment.