Unverified Commit e26fad47 authored by Jiwon Choi's avatar Jiwon Choi Committed by GitHub

[devtools] restart server pending state (#80858)

This PR adds a pending state to the clear bundler cache & server
restart.

When the user clicks the restart server button, Next.js fetches
`/__nextjs_server_status` for the current server's execution ID. Then it
queries `/__nextjs_restart_dev` middleware to trigger the server
restart, then polls the `/__nextjs_server_status` path to confirm the
server execution ID differs, which means the new server is online.

When the server has restarted, reload the window.

Closes NEXT-4562
Closes NEXT-4501

---------
Co-authored-by: 's avatarJiachi Liu <inbox@huozhi.im>
parent 5c7daf5a
...@@ -17,6 +17,7 @@ import { ...@@ -17,6 +17,7 @@ import {
type DevToolsScale, type DevToolsScale,
} from './preferences' } from './preferences'
import { ShortcutRecorder } from './shortcut-recorder' import { ShortcutRecorder } from './shortcut-recorder'
import { useRestartServer } from '../../error-overlay-toolbar/use-restart-server'
export function UserPreferences({ export function UserPreferences({
hide, hide,
...@@ -69,6 +70,7 @@ export function UserPreferencesBody({ ...@@ -69,6 +70,7 @@ export function UserPreferencesBody({
scale: DevToolsScale scale: DevToolsScale
setScale: (value: DevToolsScale) => void setScale: (value: DevToolsScale) => void
}) { }) {
const { restartServer, isPending } = useRestartServer()
const [theme, setTheme] = useState(getInitialTheme()) const [theme, setTheme] = useState(getInitialTheme())
const handleThemeChange = (e: React.ChangeEvent<HTMLSelectElement>) => { const handleThemeChange = (e: React.ChangeEvent<HTMLSelectElement>) => {
...@@ -105,21 +107,6 @@ export function UserPreferencesBody({ ...@@ -105,21 +107,6 @@ export function UserPreferencesBody({
setScale(value) setScale(value)
} }
function handleRestartDevServer(invalidatePersistentCache: boolean) {
let endpoint = '/__nextjs_restart_dev'
if (invalidatePersistentCache) {
endpoint = '/__nextjs_restart_dev?invalidatePersistentCache'
}
fetch(endpoint, {
method: 'POST',
}).then(() => {
// TODO: poll server status and reload when the server is back up.
// https://github.com/vercel/next.js/pull/80005
})
}
return ( return (
<> <>
<h2 className="dev-tools-info-section-title">General</h2> <h2 className="dev-tools-info-section-title">General</h2>
...@@ -253,8 +240,9 @@ export function UserPreferencesBody({ ...@@ -253,8 +240,9 @@ export function UserPreferencesBody({
data-restart-dev-server data-restart-dev-server
className="action-button" className="action-button"
onClick={() => onClick={() =>
handleRestartDevServer(/*invalidatePersistentCache*/ false) restartServer({ invalidatePersistentCache: false })
} }
disabled={isPending}
> >
<span>Restart</span> <span>Restart</span>
</button> </button>
...@@ -279,8 +267,9 @@ export function UserPreferencesBody({ ...@@ -279,8 +267,9 @@ export function UserPreferencesBody({
data-reset-bundler-cache data-reset-bundler-cache
className="action-button" className="action-button"
onClick={() => onClick={() =>
handleRestartDevServer(/*invalidatePersistentCache*/ true) restartServer({ invalidatePersistentCache: true })
} }
disabled={isPending}
> >
<span>Reset Cache</span> <span>Reset Cache</span>
</button> </button>
...@@ -408,6 +397,11 @@ export const DEV_TOOLS_INFO_USER_PREFERENCES_STYLES = css` ...@@ -408,6 +397,11 @@ export const DEV_TOOLS_INFO_USER_PREFERENCES_STYLES = css`
} }
} }
.preference-section button:disabled {
opacity: 0.6;
cursor: not-allowed;
}
:global(.icon) { :global(.icon) {
width: 18px; width: 18px;
height: 18px; height: 18px;
......
...@@ -5,6 +5,8 @@ import { ...@@ -5,6 +5,8 @@ import {
type OverlayDispatch, type OverlayDispatch,
} from '../../../shared' } from '../../../shared'
import type { SupportedErrorEvent } from '../../../container/runtime-error/render-error' import type { SupportedErrorEvent } from '../../../container/runtime-error/render-error'
import { useRestartServer } from './use-restart-server'
import { css } from '../../../utils/css'
/** /**
* When the Turbopack persistent cache is enabled, and the user reloads on a * When the Turbopack persistent cache is enabled, and the user reloads on a
...@@ -14,28 +16,29 @@ import type { SupportedErrorEvent } from '../../../container/runtime-error/rende ...@@ -14,28 +16,29 @@ import type { SupportedErrorEvent } from '../../../container/runtime-error/rende
* telemetry on how often this is used. * telemetry on how often this is used.
*/ */
export function RestartServerButton({ showButton }: { showButton: boolean }) { export function RestartServerButton({ showButton }: { showButton: boolean }) {
const { restartServer, isPending } = useRestartServer()
if (!showButton) { if (!showButton) {
return null return null
} }
function handleClick() {
// TODO: Use Client Action for transition indicator when DevTools is isolated.
fetch('/__nextjs_restart_dev?invalidatePersistentCache', {
method: 'POST',
}).then(() => {
// TODO: poll server status and reload when the server is back up.
// https://github.com/vercel/next.js/pull/80005
})
}
return ( return (
<button <button
className="restart-dev-server-button" className="restart-dev-server-button"
onClick={handleClick} onClick={() => restartServer({ invalidatePersistentCache: true })}
disabled={isPending}
title="Clears the bundler cache and restarts the dev server. Helpful if you are seeing stale errors or changes are not appearing." title="Clears the bundler cache and restarts the dev server. Helpful if you are seeing stale errors or changes are not appearing."
> >
<RefreshClockWise width={14} height={14} /> <RefreshClockWise
Clear Bundler Cache &amp; Restart width={14}
height={14}
style={{
animation: isPending
? 'refresh-clock-wise-spin 1s linear infinite'
: undefined,
}}
/>
Reset Bundler Cache
</button> </button>
) )
} }
...@@ -84,7 +87,7 @@ export function usePersistentCacheErrorDetection({ ...@@ -84,7 +87,7 @@ export function usePersistentCacheErrorDetection({
}, [errors, dispatch]) }, [errors, dispatch])
} }
export const RESTART_SERVER_BUTTON_STYLES = ` export const RESTART_SERVER_BUTTON_STYLES = css`
.restart-dev-server-button { .restart-dev-server-button {
display: flex; display: flex;
justify-content: center; justify-content: center;
...@@ -105,4 +108,18 @@ export const RESTART_SERVER_BUTTON_STYLES = ` ...@@ -105,4 +108,18 @@ export const RESTART_SERVER_BUTTON_STYLES = `
font-weight: 500; font-weight: 500;
line-height: var(--size-16); line-height: var(--size-16);
} }
.restart-dev-server-button:disabled {
opacity: 0.6;
cursor: not-allowed;
}
@keyframes refresh-clock-wise-spin {
from {
transform: rotate(0deg);
}
to {
transform: rotate(360deg);
}
}
` `
import { useState } from 'react'
export function useRestartServer() {
const [isPending, setIsPending] = useState(false)
const restartServer = async ({
invalidatePersistentCache,
}: {
invalidatePersistentCache: boolean
}): Promise<void> => {
setIsPending(true)
const url = invalidatePersistentCache
? '/__nextjs_restart_dev?invalidatePersistentCache=1'
: '/__nextjs_restart_dev'
let serverRestarted = false
try {
const curId = await fetch('/__nextjs_server_status')
.then((res) => res.json())
.then((data) => data.executionId as number)
.catch((error) => {
console.log(
'[Next.js DevTools] Failed to fetch server status while restarting dev server.',
error
)
return null
})
if (!curId) {
console.log(
'[Next.js DevTools] Failed to get the current server execution ID while restarting dev server.'
)
return
}
const restartRes = await fetch(url, {
method: 'POST',
})
if (!restartRes.ok) {
// Use console log to avoid spamming the error overlay which users can't control.
console.log(
'[Next.js DevTools] Failed to fetch restart server endpoint. Status:',
restartRes.status
)
return
}
// Poll for server restart confirmation.
for (let i = 0; i < 10; i++) {
// generous 1 second delay for large apps.
await new Promise((resolveTimeout) => setTimeout(resolveTimeout, 1_000))
try {
const nextId = await fetch('/__nextjs_server_status')
.then((res) => res.json())
.then((data) => data.executionId as number)
// If the execution ID has changed, the server has restarted successfully.
if (curId !== nextId) {
serverRestarted = true
// Reload the page to ensure the connection to the new server.
window.location.reload()
return
}
} catch (e) {
continue
}
}
console.log(
'[Next.js DevTools] Failed to restart server. Exhausted all polling attempts.'
)
return
} catch (error) {
console.log('[Next.js DevTools] Failed to restart server.', error)
return
} finally {
// If server restarted, don't reset isPending since the page will reload.
if (!serverRestarted) {
setIsPending(false)
}
}
}
return {
restartServer,
isPending,
}
}
...@@ -25,6 +25,7 @@ import { CALL_STACK_STYLES } from '../components/call-stack/call-stack' ...@@ -25,6 +25,7 @@ import { CALL_STACK_STYLES } from '../components/call-stack/call-stack'
import { ISSUE_FEEDBACK_BUTTON_STYLES } from '../components/errors/error-overlay-toolbar/issue-feedback-button' import { ISSUE_FEEDBACK_BUTTON_STYLES } from '../components/errors/error-overlay-toolbar/issue-feedback-button'
import { ERROR_CONTENT_SKELETON_STYLES } from '../container/runtime-error/error-content-skeleton' import { ERROR_CONTENT_SKELETON_STYLES } from '../container/runtime-error/error-content-skeleton'
import { SHORTCUT_RECORDER_STYLES } from '../components/errors/dev-tools-indicator/dev-tools-info/shortcut-recorder' import { SHORTCUT_RECORDER_STYLES } from '../components/errors/dev-tools-indicator/dev-tools-info/shortcut-recorder'
export function ComponentStyles() { export function ComponentStyles() {
return ( return (
<style> <style>
......
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