-
-
Notifications
You must be signed in to change notification settings - Fork 874
fix(dev): proxy websocket upgrades for devProxy routes with ws
#4480
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
Open
danielroe
wants to merge
1
commit into
main
Choose a base branch
from
fix/devproxy-ws-upgrade
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+154
β0
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,122 @@ | ||
| import { createServer, request, type Server } from "node:http"; | ||
| import type { AddressInfo, Socket } from "node:net"; | ||
| import type { Nitro } from "nitro/types"; | ||
| import { afterAll, beforeAll, describe, expect, it } from "vitest"; | ||
| import { NitroDevApp } from "../../src/dev/app.ts"; | ||
|
|
||
| const sockets = new Set<Socket>(); | ||
|
|
||
| function listen(server: Server): Promise<number> { | ||
| server.on("connection", (socket) => { | ||
| sockets.add(socket); | ||
| socket.on("close", () => sockets.delete(socket)); | ||
| }); | ||
| return new Promise((resolve, reject) => { | ||
| server.on("error", reject); | ||
| server.listen(0, "127.0.0.1", () => resolve((server.address() as AddressInfo).port)); | ||
| }); | ||
| } | ||
|
|
||
| /** Minimal upgrade-aware target: replies `101` then echoes raw frames. */ | ||
| function createUpgradeTarget(upgrades: string[]): Server { | ||
| const server = createServer((_req, res) => res.end("http")); | ||
| server.on("upgrade", (req, socket) => { | ||
| upgrades.push(req.url!); | ||
| socket.write( | ||
| "HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\n\r\n" | ||
| ); | ||
| socket.on("data", (chunk) => socket.write(chunk)); | ||
| }); | ||
| return server; | ||
| } | ||
|
|
||
| function upgradeRequest(port: number, path: string) { | ||
| return new Promise<{ status: number; echo: string }>((resolve, reject) => { | ||
| const req = request({ | ||
| port, | ||
| host: "127.0.0.1", | ||
| path, | ||
| headers: { Connection: "Upgrade", Upgrade: "websocket" }, | ||
| }); | ||
| const timeout = setTimeout(() => reject(new Error("upgrade timed out")), 5000); | ||
| req.on("error", reject); | ||
| req.on("response", (res) => { | ||
| clearTimeout(timeout); | ||
| reject(new Error(`unexpected HTTP response: ${res.statusCode}`)); | ||
| }); | ||
| req.on("upgrade", (res, socket) => { | ||
| socket.once("data", (chunk) => { | ||
| clearTimeout(timeout); | ||
| socket.destroy(); | ||
| resolve({ status: res.statusCode!, echo: chunk.toString() }); | ||
| }); | ||
| socket.write("ping"); | ||
| }); | ||
| req.end(); | ||
| }); | ||
| } | ||
|
|
||
| describe("dev server devProxy websocket upgrades", () => { | ||
| const upgrades: string[] = []; | ||
| const target = createUpgradeTarget(upgrades); | ||
| let devServer: Server; | ||
| let devPort: number; | ||
| let workerUpgrades = 0; | ||
|
|
||
| beforeAll(async () => { | ||
| const targetPort = await listen(target); | ||
| const app = new NitroDevApp({ | ||
| logger: console, | ||
| options: { | ||
| baseURL: "/", | ||
| devHandlers: [], | ||
| publicAssets: [], | ||
| devProxy: { | ||
| "/proxy/ws": { target: `http://127.0.0.1:${targetPort}`, ws: true }, | ||
| "/proxy/http": { target: `http://127.0.0.1:${targetPort}` }, | ||
| }, | ||
| }, | ||
| } as unknown as Nitro); | ||
| devServer = createServer(async (req, res) => { | ||
| const response = await app.fetch(new Request(`http://127.0.0.1${req.url}`)); | ||
| res.end(await response.text()); | ||
| }); | ||
| devServer.on("upgrade", (req, socket, head) => { | ||
| if (!app.proxyUpgrade(req, socket as Socket, head)) { | ||
| workerUpgrades++; | ||
| socket.destroy(); | ||
| } | ||
| }); | ||
| devPort = await listen(devServer); | ||
| }); | ||
|
|
||
| afterAll(async () => { | ||
| for (const socket of sockets) { | ||
| socket.destroy(); | ||
| } | ||
| await Promise.all([ | ||
| new Promise((resolve) => devServer.close(resolve)), | ||
| new Promise((resolve) => target.close(resolve)), | ||
| ]); | ||
| }); | ||
|
|
||
| it("proxies upgrades for a matching rule with `ws` enabled", async () => { | ||
| const res = await upgradeRequest(devPort, "/proxy/ws"); | ||
| expect(res.status).toBe(101); | ||
| expect(res.echo).toBe("ping"); | ||
| expect(upgrades).toContain("/proxy/ws"); | ||
| }); | ||
|
|
||
| it("proxies upgrades for subpaths of a matching rule", async () => { | ||
| const res = await upgradeRequest(devPort, "/proxy/ws/nested?foo=1"); | ||
| expect(res.status).toBe(101); | ||
| expect(upgrades).toContain("/proxy/ws/nested?foo=1"); | ||
| }); | ||
|
|
||
| it("forwards upgrades to the worker when no rule enables `ws`", async () => { | ||
| await expect(upgradeRequest(devPort, "/proxy/http")).rejects.toThrow(); | ||
| await expect(upgradeRequest(devPort, "/other")).rejects.toThrow(); | ||
| expect(workerUpgrades).toBe(2); | ||
| expect(upgrades).not.toContain("/proxy/http"); | ||
| }); | ||
| }); | ||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
π Performance & Scalability | π‘ Minor | β‘ Quick win
Clear the timeout on request errors.
The two expected fallback failures reject through
errorbut retain their five-second timers, unnecessarily extending the test process.Proposed fix
π Committable suggestion
π€ Prompt for AI Agents