Skip to content
Source
Sign inSign up
pingdotgg/t3code

perf(server): negotiate permessage-deflate on the websocket #4705

Mergedt3dotgg(GitHub profile, opens in a new tab)merged 3 commits intomain fromrefs/pull/4705/headmerged by t3dotgg(GitHub profile, opens in a new tab) View on GitHub

Showing 5 changed files with 128 additions and 0 deletions (loading 1).

x
0 of 5 viewed, 5 left
28 additions and 0 deletionsapps/server/src/server.test.tsModified
View file
@@ -3081,6 +3081,34 @@
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
+ it.effect("negotiates permessage-deflate with clients that offer it", () =>
+ Effect.gen(function* () {
+ yield* buildAppUnderTest();
+​
+ const { cookie, url } = parseSessionCookieFromWsUrl(yield* getWsServerUrl("/ws"));
+ const openSocket = (perMessageDeflate: boolean) =>
+ Effect.acquireRelease(
+ Effect.callback<NodeSocket.NodeWS.WebSocket, Error>((resume) => {
+ const socket = new NodeSocket.NodeWS.WebSocket(url, {
+ perMessageDeflate,
+ ...(cookie ? { headers: { cookie } } : {}),
+ });
+ socket.on("open", () => resume(Effect.succeed(socket)));
+ socket.on("error", (error) => resume(Effect.fail(error)));
+ }),
+ (socket) => Effect.sync(() => socket.close()),
+ );
Thread on lines 3089 to 3100
coderabbitai[bot](GitHub profile, opens in a new tab)commented

🩺 Stability & Availability | 🟡 Minor | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "Changed files/stat:"
git diff --stat || true

echo
echo "Locate test file and relevant lines:"
wc -l apps/server/src/server.test.ts
sed -n '3060,3130p' apps/server/src/server.test.ts

echo
echo "Search for openSocket usages and related tests:"
rg -n "openSocket|perMessageDeflate|NodeWs|NodeWS|layerTest|NodeServer|close event|Effect\.acquireRelease" apps/server/src/server.test.ts

echo
echo "Package WebSocket dependencies:"
if [ -f package.json ]; then jq '.dependencies, .devDependencies' package.json | rg -i 'ws|`@ff-labs/fff-node`|bun|node' || true; fi
fd -a 'package.json' . | while read -r f; do
  echo "--- ${f#"$PWD/"}"
  jq -r 'select(.dependencies or .devDependencies) as $d
    | {"path": env.SUBJECT_FILE, "deps": ($d.dependencies // {}), "dev": ($d.devDependencies // {})}
    | with_entries(select(.value|keys[]?|test("^(ws|`@ff-labs/fff-node`)$";"i")?))' "$f" || true
done

Repository: pingdotgg/t3code

Length of output: 12844


🏁 Script executed:

#!/bin/bash
set -euo pipefail

# Behavioral probe: if test workspace has ws installed, demonstrate close() starts handshake and close event arrives after it.
# Otherwise print availability context without executing repository test code.
echo "Node version:"
node --version || true
echo "Probe: ws availability"
node - <<'JS'
try {
  const wsPkg = require('ws');
  const server = require('ws');
  console.log("ws version:", wsPkg.version);
  const WebSocket = server.WebSocket;
  const wss = new server.WebSocketServer({ port: 0 }, () => {
    const url = `ws://localhost:${wss.address().port}`;
    console.log("server url:", url);
    const client = new WebSocket(url, { perMessageDeflate: false });
    let events;
    client.on("open", () => {
      events.push(["open"]);
      client.close();
    });
    client.on("close", (code, reason) => {
      events.push(["close", code, reason && reason.toString()]);
      console.log(JSON.stringify(events));
    });
    client.on("error", (err) => {
      console.log("error", err.message);
    });
    console.log("events immediate after close init:", events);
  });
} catch (err) {
  console.log("ws not available in node_modules:", err && err.message);
}
JS

Repository: pingdotgg/t3code

Length of output: 302


🌐 Web query:

ws WebSocket close event close method asynchronous close handshake documentation

💡 Result:

The WebSocket closing handshake is a standardized mechanism defined in RFC 6455 to ensure that both peers are aware that the connection is being terminated, allowing for the graceful handling of pending data [1]. In the context of the popular Node.js ws library, the websocket.close([code[, reason]]) method initiates this closing handshake [2][3]. It is important to note that while the closing handshake is an asynchronous process in the WebSocket protocol, the ws library's close method itself is synchronous in terms of function execution—it immediately triggers the protocol's closing sequence [2][3]. It does not return a Promise or take a completion callback to signal when the handshake has finished [2][3]. Instead, the completion of the handshake is signaled by the 'close' event, which is emitted once the connection has been fully closed [2][3][4]. Key distinctions regarding closing methods: 1. websocket.close: This initiates the graceful closing handshake [4]. It allows for pending messages to be sent before the handshake begins and waits for the corresponding close frame from the other peer [5][6]. 2. websocket.terminate: This is an alternative method that immediately destroys the underlying socket connection without performing the closing handshake [4]. It is typically used for error handling or when an immediate shutdown is required regardless of the state of pending data [7][4]. While libraries in other environments (such as.NET with CloseAsync or Boost.Beast with async_close) explicitly expose the asynchronous nature of the handshake via Promises or completion handlers [8][9], the standard Web API close and the Node.js ws library's close method are designed to be invoked as fire-and-forget actions that lead to a later 'close' event [5][3][6].

Citations:


Await the sockets’ close events in the finalizer.

WebSocket.close() initiates an asynchronous closing handshake; wrapping it in Effect.sync lets the scope finish immediately after calling close(), before the close event signals the socket is actually terminated. Await the close event in the finalizer with a bounded termination fallback to avoid leaving unclosed WebSocket handles during teardown. (github.com)

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@apps/server/src/server.test.ts` around lines 3089 - 3100, Update the
finalizer of openSocket to await the WebSocket close event after calling
socket.close(), rather than completing immediately via Effect.sync. Add a
bounded fallback so teardown still completes if the close event never arrives,
while preserving the existing socket acquisition and error handling.
+​
+ const compressed = yield* openSocket(true);
+ // The ws client records the negotiated extension only when the server's
+ // 101 response accepted the offer.
+ assert.include(compressed.extensions, "permessage-deflate");
+​
+ const plain = yield* openSocket(false);
+ assert.notInclude(plain.extensions, "permessage-deflate");