-
Notifications
You must be signed in to change notification settings - Fork 3
✨ Add WebSocket server to @effectionx/websocket #222
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
taras
wants to merge
9
commits into
main
Choose a base branch
from
feat/websocket-server
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.
Open
Changes from all commits
Commits
Show all changes
9 commits
Select commit
Hold shift + click to select a range
aee6d2f
✨ Add WebSocket server to @effectionx/websocket
taras 1319a81
🐛 Fix strict typecheck in server test message assertion
taras 61f849d
♻️ Use on/once from @effectionx/node for server events
taras af5c837
🏷️ Add explicit types to WebSocketResource.send
taras 118813f
♻️ Drop redundant per-connection task in websocket server
taras 9191267
✅ Cover close code/reason propagation and accept-queue buffering
taras e4921e9
✨ Bound websocket teardown with a close timeout (timebox)
taras d1f246f
✨ Add composable close(code, reason) + going-away server shutdown
taras 3822ca5
✨ Isolate per-connection errors with scoped + errors stream
taras 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
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
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 |
|---|---|---|
| @@ -1 +1,2 @@ | ||
| export * from "./websocket.ts"; | ||
| export * from "./server.ts"; |
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,254 @@ | ||
| import { createServer } from "node:http"; | ||
| import type { AddressInfo } from "node:net"; | ||
| import { describe, it } from "@effectionx/vitest"; | ||
| import { | ||
| type Operation, | ||
| type Subscription, | ||
| createQueue, | ||
| resource, | ||
| spawn, | ||
| suspend, | ||
| withResolvers, | ||
| } from "effection"; | ||
| import { expect } from "expect"; | ||
| import { WebSocketServer, type WebSocket as WsWebSocket } from "ws"; | ||
|
|
||
| import { | ||
| type WebSocketServerLike, | ||
| type WebSocketServerResource, | ||
| useWebSocketServer, | ||
| } from "./server.ts"; | ||
| import { type WebSocketResource, useWebSocket } from "./websocket.ts"; | ||
|
|
||
| describe("WebSocketServer", () => { | ||
| it("yields a connection and receives a message from the client", function* () { | ||
| let { server, port } = yield* useTestServer(); | ||
| let incoming = yield* server; | ||
|
|
||
| let client = yield* connect(port); | ||
| let connection = (yield* incoming.next()).value; | ||
|
|
||
| let messages = yield* connection; | ||
| yield* client.send("hello from client"); | ||
|
|
||
| let { value } = yield* messages.next(); | ||
| expect(value).toMatchObject({ data: "hello from client" }); | ||
| }); | ||
|
|
||
| it("sends a message from a server connection to the client", function* () { | ||
| let { server, port } = yield* useTestServer(); | ||
| let incoming = yield* server; | ||
|
|
||
| let client = yield* connect(port); | ||
| let connection = (yield* incoming.next()).value; | ||
|
|
||
| let clientMessages = yield* client; | ||
| yield* connection.send("hello from server"); | ||
|
|
||
| let { value } = yield* clientMessages.next(); | ||
| expect(value).toMatchObject({ data: "hello from server" }); | ||
| }); | ||
|
|
||
| it("completes a connection stream when its client disconnects", function* () { | ||
| let { server, port } = yield* useTestServer(); | ||
| let incoming = yield* server; | ||
|
|
||
| let raw = new WebSocket(`ws://localhost:${port}`); | ||
| yield* useWebSocket<string>(() => raw); | ||
| let connection = (yield* incoming.next()).value; | ||
| let messages = yield* connection; | ||
|
|
||
| raw.close(4001, "goodbye"); | ||
|
|
||
| let event = yield* drain(messages); | ||
| expect(event.type).toEqual("close"); | ||
| expect(event.wasClean).toEqual(true); | ||
| expect(event.code).toEqual(4001); | ||
| expect(event.reason).toEqual("goodbye"); | ||
| }); | ||
|
|
||
| it("closes live client connections when the server is torn down", function* () { | ||
| let { httpServer, port } = yield* useHttp(); | ||
| let accepted = createQueue<void, never>(); | ||
|
|
||
| let serverTask = yield* spawn(function* () { | ||
| let server = yield* useWebSocketServer<string>( | ||
| () => | ||
| new WebSocketServer({ | ||
| server: httpServer, | ||
| }) as unknown as WebSocketServerLike, | ||
| ); | ||
| let incoming = yield* server; | ||
| yield* incoming.next(); | ||
| accepted.add(); | ||
| yield* suspend(); | ||
| }); | ||
|
|
||
| let client = yield* connect(port); | ||
| let messages = yield* client; | ||
|
|
||
| // wait until the server has accepted the connection before tearing it down | ||
| yield* accepted.next(); | ||
| yield* serverTask.halt(); | ||
|
|
||
| let event = yield* drain(messages); | ||
| expect(event.type).toEqual("close"); | ||
| expect(event.wasClean).toEqual(true); | ||
| expect(event.code).toEqual(1001); | ||
| expect(event.reason).toEqual("server shutting down"); | ||
| }); | ||
|
|
||
| it("closes a connection with an explicit code and reason", function* () { | ||
| let { server, port } = yield* useTestServer(); | ||
| let incoming = yield* server; | ||
|
|
||
| let client = yield* connect(port); | ||
| let connection = (yield* incoming.next()).value; | ||
| let clientMessages = yield* client; | ||
|
|
||
| yield* connection.close(4002, "custom"); | ||
|
|
||
| let event = yield* drain(clientMessages); | ||
| expect(event.code).toEqual(4002); | ||
| expect(event.reason).toEqual("custom"); | ||
| }); | ||
|
|
||
| it("buffers a connection that arrives before it is consumed", function* () { | ||
| let { server, port } = yield* useTestServer(); | ||
|
|
||
| // connect the client before subscribing to the server stream | ||
| let client = yield* connect(port); | ||
| let incoming = yield* server; | ||
|
|
||
| // the connection was buffered while nobody was subscribed | ||
| let connection = (yield* incoming.next()).value; | ||
|
|
||
| let messages = yield* connection; | ||
| yield* client.send("buffered hello"); | ||
|
|
||
| let { value } = yield* messages.next(); | ||
| expect(value).toMatchObject({ data: "buffered hello" }); | ||
| }); | ||
|
|
||
| it("isolates a connection error so the server keeps serving other clients", function* () { | ||
| let { httpServer, port } = yield* useHttp(); | ||
|
|
||
| // capture the raw accepted sockets so we can force an error on one | ||
| let wss = new WebSocketServer({ server: httpServer }); | ||
| let rawSockets = createQueue<WsWebSocket, never>(); | ||
| wss.on("connection", (ws) => rawSockets.add(ws)); | ||
|
|
||
| let server = yield* useWebSocketServer<string>( | ||
| () => wss as unknown as WebSocketServerLike, | ||
| ); | ||
| let incoming = yield* server; | ||
| let serverErrors = yield* server.errors; | ||
|
|
||
| // accept one client, then make its underlying socket error | ||
| yield* connect(port); | ||
| yield* incoming.next(); | ||
| let raw = (yield* rawSockets.next()).value; | ||
| raw.emit("error", new Error("boom")); | ||
|
|
||
| // the failure is surfaced on the errors stream, not thrown at the server. | ||
| // A socket failure surfaces as the DOM `error` event, whose message is the | ||
| // underlying error's message. | ||
| let { value: error } = yield* serverErrors.next(); | ||
| expect((error as ErrorEvent).message).toContain("boom"); | ||
|
|
||
| // and the server survives, serving a fresh client | ||
| let client = yield* connect(port); | ||
| let connection = (yield* incoming.next()).value; | ||
| let messages = yield* connection; | ||
| yield* client.send("still alive"); | ||
| let { value } = yield* messages.next(); | ||
| expect(value).toMatchObject({ data: "still alive" }); | ||
| }); | ||
|
|
||
| it("surfaces each simultaneous client as a distinct connection", function* () { | ||
| let { server, port } = yield* useTestServer(); | ||
| let incoming = yield* server; | ||
|
|
||
| // connect two clients, then read two buffered connections back out | ||
| let clientA = yield* connect(port); | ||
| let clientB = yield* connect(port); | ||
|
|
||
| let first = (yield* incoming.next()).value; | ||
| let second = (yield* incoming.next()).value; | ||
|
|
||
| expect(first).not.toBe(second); | ||
|
|
||
| // each connection receives only its own client's message, regardless of order | ||
| let firstMessages = yield* first; | ||
| let secondMessages = yield* second; | ||
|
|
||
| yield* clientA.send("A"); | ||
| yield* clientB.send("B"); | ||
|
|
||
| let received = [ | ||
| ((yield* firstMessages.next()).value as MessageEvent<string>).data, | ||
| ((yield* secondMessages.next()).value as MessageEvent<string>).data, | ||
| ].sort(); | ||
|
coderabbitai[bot] marked this conversation as resolved.
|
||
|
|
||
| expect(received).toEqual(["A", "B"]); | ||
| }); | ||
| }); | ||
|
|
||
| interface TestServer { | ||
| server: WebSocketServerResource<string>; | ||
| port: number; | ||
| } | ||
|
|
||
| function useTestServer(): Operation<TestServer> { | ||
| return resource(function* (provide) { | ||
| let { httpServer, port } = yield* useHttp(); | ||
|
|
||
| let server = yield* useWebSocketServer<string>( | ||
| () => | ||
| new WebSocketServer({ | ||
| server: httpServer, | ||
| }) as unknown as WebSocketServerLike, | ||
| ); | ||
|
|
||
| yield* provide({ server, port }); | ||
| }); | ||
| } | ||
|
|
||
| function useHttp(): Operation<{ | ||
| httpServer: ReturnType<typeof createServer>; | ||
| port: number; | ||
| }> { | ||
| return resource(function* (provide) { | ||
| let httpServer = createServer(); | ||
|
|
||
| let listening = withResolvers<void>(); | ||
| httpServer.listen(0, listening.resolve); | ||
| yield* listening.operation; | ||
|
|
||
| let port = (httpServer.address() as AddressInfo).port; | ||
|
|
||
| try { | ||
| yield* provide({ httpServer, port }); | ||
| } finally { | ||
| let closed = withResolvers<void>(); | ||
| httpServer.close(() => closed.resolve()); | ||
| yield* closed.operation; | ||
| } | ||
| }); | ||
| } | ||
|
|
||
| function* connect(port: number): Operation<WebSocketResource<string>> { | ||
| return yield* useWebSocket<string>( | ||
| () => new WebSocket(`ws://localhost:${port}`), | ||
| ); | ||
| } | ||
|
|
||
| function* drain<T, TClose>( | ||
| subscription: Subscription<T, TClose>, | ||
| ): Operation<TClose> { | ||
| let next = yield* subscription.next(); | ||
| while (!next.done) { | ||
| next = yield* subscription.next(); | ||
| } | ||
| return next.value; | ||
| } | ||
Oops, something went wrong.
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.
🎯 Functional Correctness | 🟠 Major | ⚡ Quick win
🧩 Analysis chain
🏁 Script executed:
Repository: thefrontside/effectionx
Length of output: 1604
🏁 Script executed:
Repository: thefrontside/effectionx
Length of output: 1497
🏁 Script executed:
Repository: thefrontside/effectionx
Length of output: 546
🏁 Script executed:
Repository: thefrontside/effectionx
Length of output: 20994
🏁 Script executed:
Repository: thefrontside/effectionx
Length of output: 9186
Avoid a hard dependency on
@effectionx/nodeinwebsocket/package.json. Its top-level entrypoint reexportsnode/stream.ts, so importing@effectionx/websocketpulls innode:streameven for browser/Deno consumers. Import@effectionx/node/eventsinstead, or split the event helpers from the Node-only stream adapter.🤖 Prompt for AI Agents