Unverified Commit 6c3577d7 authored by Wyatt Johnson's avatar Wyatt Johnson Committed by GitHub

fix: ensure websockets are correctly passed (#65759)

Further enhancing the typings across the codebase, this resolves some
errors discovered while running tests. During development, previously,
if the websocket request was forwarded down to the route resolver, it
would fail. This is because a `Duplex` stream is not a `ServerResponse`.

I opted to use the `MockedResponse` here to ensure the remaining code
didn't change, as we're only using the resolve routes code to identify a
match rather than actually sending the response on. The response data is
sent later with the `proxyRequest` which here does have support for
`Duplex` streams.
parent 337666bf
...@@ -40,6 +40,7 @@ import { ensureLeadingSlash } from '../../shared/lib/page-path/ensure-leading-sl ...@@ -40,6 +40,7 @@ import { ensureLeadingSlash } from '../../shared/lib/page-path/ensure-leading-sl
import { getNextPathnameInfo } from '../../shared/lib/router/utils/get-next-pathname-info' import { getNextPathnameInfo } from '../../shared/lib/router/utils/get-next-pathname-info'
import { getHostname } from '../../shared/lib/get-hostname' import { getHostname } from '../../shared/lib/get-hostname'
import { detectDomainLocale } from '../../shared/lib/i18n/detect-domain-locale' import { detectDomainLocale } from '../../shared/lib/i18n/detect-domain-locale'
import { MockedResponse } from './mock-request'
const debug = setupDebug('next:router-server:main') const debug = setupDebug('next:router-server:main')
const isNextFont = (pathname: string | null) => const isNextFont = (pathname: string | null) =>
...@@ -660,9 +661,16 @@ export async function initialize(opts: { ...@@ -660,9 +661,16 @@ export async function initialize(opts: {
} }
} }
const res = new MockedResponse({
resWriter: () => {
throw new Error(
'Invariant: did not expect response writer to be written to for upgrade request'
)
},
})
const { matchedOutput, parsedUrl } = await resolveRoutes({ const { matchedOutput, parsedUrl } = await resolveRoutes({
req, req,
res: socket as any, res,
isUpgradeReq: true, isUpgradeReq: true,
signal: signalFromNodeResponse(socket), signal: signalFromNodeResponse(socket),
}) })
...@@ -674,7 +682,7 @@ export async function initialize(opts: { ...@@ -674,7 +682,7 @@ export async function initialize(opts: {
} }
if (parsedUrl.protocol) { if (parsedUrl.protocol) {
return await proxyRequest(req, socket as any, parsedUrl, head) return await proxyRequest(req, socket, parsedUrl, head)
} }
// If there's no matched output, we don't handle the request as user's // If there's no matched output, we don't handle the request as user's
......
...@@ -3,12 +3,14 @@ import type { NextUrlWithParsedQuery } from '../../request-meta' ...@@ -3,12 +3,14 @@ import type { NextUrlWithParsedQuery } from '../../request-meta'
import url from 'url' import url from 'url'
import { stringifyQuery } from '../../server-route-utils' import { stringifyQuery } from '../../server-route-utils'
import { Duplex } from 'stream'
import { DetachedPromise } from '../../../lib/detached-promise'
export async function proxyRequest( export async function proxyRequest(
req: IncomingMessage, req: IncomingMessage,
res: ServerResponse, res: ServerResponse | Duplex,
parsedUrl: NextUrlWithParsedQuery, parsedUrl: NextUrlWithParsedQuery,
upgradeHead?: any, upgradeHead?: Buffer,
reqBody?: any, reqBody?: any,
proxyTimeout?: number | null proxyTimeout?: number | null
) { ) {
...@@ -33,7 +35,6 @@ export async function proxyRequest( ...@@ -33,7 +35,6 @@ export async function proxyRequest(
}, },
}) })
await new Promise((proxyResolve, proxyReject) => {
let finished = false let finished = false
// http-proxy does not properly detect a client disconnect in newer // http-proxy does not properly detect a client disconnect in newer
...@@ -46,6 +47,7 @@ export async function proxyRequest( ...@@ -46,6 +47,7 @@ export async function proxyRequest(
proxy.on('proxyReq', (proxyReq) => { proxy.on('proxyReq', (proxyReq) => {
res.on('close', () => proxyReq.destroy()) res.on('close', () => proxyReq.destroy())
}) })
proxy.on('proxyRes', (proxyRes) => { proxy.on('proxyRes', (proxyRes) => {
if (res.destroyed) { if (res.destroyed) {
proxyRes.destroy() proxyRes.destroy()
...@@ -73,37 +75,48 @@ export async function proxyRequest( ...@@ -73,37 +75,48 @@ export async function proxyRequest(
innerRes.once('close', cleanup) innerRes.once('close', cleanup)
}) })
const detached = new DetachedPromise<boolean>()
// When the proxy finishes proxying the request, shut down the proxy.
detached.promise.finally(() => {
proxy.close()
})
proxy.on('error', (err) => { proxy.on('error', (err) => {
console.error(`Failed to proxy ${target}`, err) console.error(`Failed to proxy ${target}`, err)
if (!finished) { if (!finished) {
finished = true finished = true
proxyReject(err) detached.reject(err)
if (!res.destroyed) { if (!res.destroyed) {
if (!(res instanceof Duplex)) {
res.statusCode = 500 res.statusCode = 500
}
res.end('Internal Server Error') res.end('Internal Server Error')
} }
} }
}) })
// if upgrade head is present treat as WebSocket request // If upgrade head is present or the response is a Duplex stream, treat as
if (upgradeHead) { // WebSocket request.
if (upgradeHead || res instanceof Duplex) {
proxy.on('proxyReqWs', (proxyReq) => { proxy.on('proxyReqWs', (proxyReq) => {
proxyReq.on('close', () => { proxyReq.on('close', () => {
if (!finished) { if (!finished) {
finished = true finished = true
proxyResolve(true) detached.resolve(true)
} }
}) })
}) })
proxy.ws(req as any as IncomingMessage, res, upgradeHead) proxy.ws(req, res, upgradeHead)
proxyResolve(true) detached.resolve(true)
} else { } else {
proxy.on('proxyReq', (proxyReq) => { proxy.on('proxyReq', (proxyReq) => {
proxyReq.on('close', () => { proxyReq.on('close', () => {
if (!finished) { if (!finished) {
finished = true finished = true
proxyResolve(true) detached.resolve(true)
} }
}) })
}) })
...@@ -111,5 +124,6 @@ export async function proxyRequest( ...@@ -111,5 +124,6 @@ export async function proxyRequest(
buffer: reqBody, buffer: reqBody,
}) })
} }
})
return detached.promise
} }
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