Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: use websocket to test server liveness before client reload #17891

Merged
merged 19 commits into from
Oct 25, 2024
Merged
Show file tree
Hide file tree
Changes from 10 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 12 additions & 17 deletions packages/vite/src/client/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -331,24 +331,19 @@ async function waitForSuccessfulPing(
hostAndPath: string,
ms = 1000,
) {
const pingHostProtocol = socketProtocol === 'wss' ? 'https' : 'http'

const ping = async () => {
// A fetch on a websocket URL will return a successful promise with status 400,
// but will reject a networking error.
// When running on middleware mode, it returns status 426, and an cors error happens if mode is not no-cors
try {
await fetch(`${pingHostProtocol}://${hostAndPath}`, {
mode: 'no-cors',
headers: {
// Custom headers won't be included in a request with no-cors so (ab)use one of the
// safelisted headers to identify the ping request
Accept: 'text/x-vite-ping',
},
async function ping() {
const socket = new WebSocket(
`${socketProtocol}://${hostAndPath}`,
'vite-ping',
)
return new Promise<boolean>((resolve) => {
sapphi-red marked this conversation as resolved.
Show resolved Hide resolved
socket.addEventListener('open', () => {
resolve(true)
})
return true
} catch {}
return false
socket.addEventListener('error', () => {
resolve(false)
})
})
}

if (await ping()) {
Expand Down
7 changes: 6 additions & 1 deletion packages/vite/src/node/server/ws.ts
Original file line number Diff line number Diff line change
Expand Up @@ -133,7 +133,9 @@ export function createWebSocketServer(
wss = new WebSocketServerRaw({ noServer: true })
hmrServerWsListener = (req, socket, head) => {
if (
req.headers['sec-websocket-protocol'] === HMR_HEADER &&
[HMR_HEADER, 'vite-ping'].includes(
req.headers['sec-websocket-protocol']!,
) &&
req.url === hmrBase
) {
wss.handleUpgrade(req, socket as Socket, head, (ws) => {
Expand Down Expand Up @@ -168,6 +170,9 @@ export function createWebSocketServer(
}

wss.on('connection', (socket) => {
if (socket.protocol === 'vite-ping') {
return
}
socket.on('message', (raw) => {
if (!customListeners.size) return
let parsed: any
Expand Down
78 changes: 78 additions & 0 deletions playground/client-reload/__tests__/client-reload.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
import path from 'node:path'
import { type ServerOptions, type ViteDevServer, createServer } from 'vite'
import { afterEach, describe, expect, test } from 'vitest'
import { hmrPorts, isServe, page, ports } from '~utils'

let server: ViteDevServer

afterEach(async () => {
await server?.close()
})

async function testClientReload(serverOptions: ServerOptions) {
// start server
server = await createServer({
root: path.resolve(import.meta.dirname, '..'),
logLevel: 'silent',
server: {
strictPort: true,
...serverOptions,
},
})

await server.listen()
const serverUrl = server.resolvedUrls.local[0]

// open page and wait for connection
const connectedPromise = page.waitForEvent('console', {
predicate: (message) => message.text().includes('[vite] connected.'),
timeout: 5000,
})
await page.goto(serverUrl)
await connectedPromise

// input state
await page.locator('input').fill('hello')

// restart and wait for reconnection after reload
const reConnectedPromise = page.waitForEvent('console', {
predicate: (message) => message.text().includes('[vite] connected.'),
timeout: 5000,
})
await server.restart()
await reConnectedPromise
expect(await page.textContent('input')).toBe('')
}

// TODO:
// running all tests together is flaky.
// for now, run only the last one with retry.
describe.runIf(isServe)('client-reload', () => {
test.skip('default', async () => {
await testClientReload({
port: ports['client-reload'],
})
})

test.skip('custom hmr port', async () => {
await testClientReload({
port: ports['client-reload/hmr-port'],
hmr: {
port: hmrPorts['client-reload/hmr-port'],
},
})
})

test('custom hmr port and cross origin isolation', { retry: 2 }, async () => {
await testClientReload({
port: ports['client-reload/cross-origin'],
hmr: {
port: hmrPorts['client-reload/cross-origin'],
},
headers: {
'Cross-Origin-Embedder-Policy': 'require-corp',
'Cross-Origin-Opener-Policy': 'same-origin',
},
})
})
})
6 changes: 6 additions & 0 deletions playground/client-reload/__tests__/serve.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
// do nothing here since server is managed inside spec
export async function serve(): Promise<{ close(): Promise<void> }> {
return {
close: () => Promise.resolve(),
}
}
4 changes: 4 additions & 0 deletions playground/client-reload/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
<body>
<h4>Test Client Reload</h4>
<input />
</body>
12 changes: 12 additions & 0 deletions playground/client-reload/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
{
"name": "@vitejs/test-client-reload",
"private": true,
"version": "0.0.0",
"type": "module",
"scripts": {
"debug": "node --inspect-brk ../../packages/vite/bin/vite",
"dev": "vite",
"build": "vite build",
"preview": "vite preview"
}
}
5 changes: 5 additions & 0 deletions playground/client-reload/vite.config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
import { defineConfig } from 'vite'

export default defineConfig({
server: {},
})
5 changes: 5 additions & 0 deletions playground/test-utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,9 @@ export const ports = {
'css/dynamic-import': 5007,
'css/lightningcss-proxy': 5008,
'backend-integration': 5009,
'client-reload': 5010,
'client-reload/hmr-port': 5011,
'client-reload/cross-origin': 5012,
}
export const hmrPorts = {
'optimize-missing-deps': 24680,
Expand All @@ -58,6 +61,8 @@ export const hmrPorts = {
'css/lightningcss-proxy': 24686,
json: 24687,
'ssr-conditions': 24688,
'client-reload/hmr-port': 24689,
'client-reload/cross-origin': 24690,
}

const hexToNameMap: Record<string, string> = {}
Expand Down
2 changes: 2 additions & 0 deletions pnpm-lock.yaml

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