-
-
Notifications
You must be signed in to change notification settings - Fork 40
feat: add fromNodeUpgradeHandler util + socket.io example
#185
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
Merged
Merged
Changes from 3 commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
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
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,64 @@ | ||
| import type { IncomingMessage } from "node:http"; | ||
| import type { Duplex } from "node:stream"; | ||
| import type { Hooks } from "./hooks.ts"; | ||
|
|
||
| /** | ||
| * A Node.js `(req, socket, head)` upgrade handler. | ||
| */ | ||
| export type NodeUpgradeHandler = ( | ||
| req: IncomingMessage, | ||
| socket: Duplex, | ||
| head: Buffer, | ||
| ) => void | Promise<void>; | ||
|
|
||
| /** | ||
| * Wrap a Node.js `(req, socket, head)` upgrade handler as a {@link Hooks} | ||
| * object that can be mounted via `crossws/server/node`. | ||
| * | ||
| * The wrapped handler takes ownership of the socket; crossws's other | ||
| * lifecycle hooks (`open`/`message`/`close`/`error`) are **not** invoked | ||
| * for connections routed through it. | ||
| * | ||
| * @example | ||
| * ```ts | ||
| * import { WebSocketServer } from "ws"; | ||
| * import { fromNodeUpgradeHandler } from "crossws/adapters/node"; | ||
| * import { serve } from "crossws/server/node"; | ||
| * | ||
| * const wss = new WebSocketServer({ noServer: true }); | ||
| * wss.on("connection", (ws) => { | ||
| * ws.on("message", (data) => ws.send(data)); | ||
| * }); | ||
| * | ||
| * serve({ | ||
| * websocket: fromNodeUpgradeHandler((req, socket, head) => { | ||
| * wss.handleUpgrade(req, socket, head, (ws) => { | ||
| * wss.emit("connection", ws, req); | ||
| * }); | ||
| * }), | ||
| * fetch: () => new Response("ok"), | ||
| * }); | ||
| * ``` | ||
| */ | ||
| export function fromNodeUpgradeHandler( | ||
| handler: NodeUpgradeHandler, | ||
| ): Partial<Hooks> { | ||
| return { | ||
| async upgrade(request) { | ||
| const node = (request as { runtime?: { node?: NodeUpgradeCtx } }).runtime | ||
| ?.node; | ||
| if (!node?.upgrade) { | ||
| throw new Error( | ||
| "[crossws] `fromNodeUpgradeHandler` must be mounted via `crossws/server/node`.", | ||
| ); | ||
| } | ||
| await handler(node.req, node.upgrade.socket, node.upgrade.head); | ||
| return { handled: true }; | ||
| }, | ||
| }; | ||
| } | ||
|
|
||
| interface NodeUpgradeCtx { | ||
| req: IncomingMessage; | ||
| upgrade?: { socket: Duplex; head: Buffer }; | ||
| } |
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,115 @@ | ||
| import { once } from "node:events"; | ||
| import { getRandomPort } from "get-port-please"; | ||
| import { afterEach, beforeEach, expect, test } from "vitest"; | ||
| import { WebSocketServer } from "ws"; | ||
| import WebSocket from "ws"; | ||
| import { fromNodeUpgradeHandler } from "../src/node-handler.ts"; | ||
| import { serve } from "../src/server/node.ts"; | ||
|
|
||
| type ServeReturn = ReturnType<typeof serve>; | ||
|
|
||
| let currentServer: ServeReturn | undefined; | ||
| let currentWss: WebSocketServer | undefined; | ||
| let unhandled: unknown[] = []; | ||
|
|
||
| function onUnhandled(err: unknown) { | ||
| unhandled.push(err); | ||
| } | ||
|
|
||
| beforeEach(() => { | ||
| unhandled = []; | ||
| process.on("unhandledRejection", onUnhandled); | ||
| process.on("uncaughtException", onUnhandled); | ||
| }); | ||
|
|
||
| afterEach(async () => { | ||
| process.off("unhandledRejection", onUnhandled); | ||
| process.off("uncaughtException", onUnhandled); | ||
| currentWss?.close(); | ||
| await currentServer?.close(true); | ||
| currentServer = undefined; | ||
| currentWss = undefined; | ||
| // Give any stray async errors a tick to surface before asserting. | ||
| await new Promise((r) => setImmediate(r)); | ||
| if (unhandled.length > 0) { | ||
| throw new AggregateError( | ||
| unhandled as Error[], | ||
| `Unexpected unhandled errors during test: ${unhandled | ||
| .map((e) => (e as Error)?.message ?? String(e)) | ||
| .join("; ")}`, | ||
| ); | ||
| } | ||
| }); | ||
|
|
||
| test("fromNodeUpgradeHandler delegates upgrade to a ws.WebSocketServer", async () => { | ||
| const wss = new WebSocketServer({ noServer: true }); | ||
| currentWss = wss; | ||
| const receivedOnUpstream: string[] = []; | ||
| wss.on("connection", (ws) => { | ||
| ws.on("message", (data) => { | ||
| receivedOnUpstream.push(data.toString()); | ||
| ws.send(`echo:${data.toString()}`); | ||
| }); | ||
| }); | ||
|
|
||
| const port = await getRandomPort("localhost"); | ||
| const server = serve({ | ||
| port, | ||
| hostname: "127.0.0.1", | ||
| fetch: () => new Response("ok"), | ||
| websocket: fromNodeUpgradeHandler((req, socket, head) => { | ||
| wss.handleUpgrade(req, socket, head, (ws) => { | ||
| wss.emit("connection", ws, req); | ||
| }); | ||
| }), | ||
| }); | ||
| currentServer = server; | ||
| await server.ready(); | ||
|
|
||
| const client = new WebSocket(`ws://127.0.0.1:${port}/`); | ||
| await once(client, "open"); | ||
| client.send("hello"); | ||
| const [reply] = await once(client, "message"); | ||
| expect(reply.toString()).toBe("echo:hello"); | ||
| expect(receivedOnUpstream).toEqual(["hello"]); | ||
| client.close(); | ||
| await once(client, "close"); | ||
| }); | ||
|
|
||
| test("fromNodeUpgradeHandler does not invoke node adapter's own handleUpgrade", async () => { | ||
| // If the handoff sentinel is ignored, the node adapter would try to run | ||
| // ws.handleUpgrade on a socket that the user's handler has already taken | ||
| // over — the client would see a connection failure or duplicate upgrade. | ||
| // This test catches that regression by asserting the upstream handler is | ||
| // the *only* thing that opens the WebSocket. | ||
| const wss = new WebSocketServer({ noServer: true }); | ||
| currentWss = wss; | ||
| let upstreamOpens = 0; | ||
| wss.on("connection", (ws) => { | ||
| upstreamOpens++; | ||
| ws.on("message", (data) => ws.send(data)); | ||
| }); | ||
|
|
||
| const port = await getRandomPort("localhost"); | ||
| const server = serve({ | ||
| port, | ||
| hostname: "127.0.0.1", | ||
| fetch: () => new Response("ok"), | ||
| websocket: fromNodeUpgradeHandler((req, socket, head) => { | ||
| wss.handleUpgrade(req, socket, head, (ws) => { | ||
| wss.emit("connection", ws, req); | ||
| }); | ||
| }), | ||
| }); | ||
| currentServer = server; | ||
| await server.ready(); | ||
|
|
||
| const client = new WebSocket(`ws://127.0.0.1:${port}/`); | ||
| await once(client, "open"); | ||
| client.send("ping"); | ||
| const [reply] = await once(client, "message"); | ||
| expect(reply.toString()).toBe("ping"); | ||
| expect(upstreamOpens).toBe(1); | ||
| client.close(); | ||
| await once(client, "close"); | ||
| }); |
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.
Uh oh!
There was an error while loading. Please reload this page.