Skip to content

fix(wsLink): wsLink should await for connectionParams before sending … - #6547

Merged
KATT merged 8 commits into
nextfrom
fix/6546-wsLink-not-waiting-for-urlConnectionParams
Feb 24, 2025
Merged

KATT merged 8 commits into
nextfrom
fix/6546-wsLink-not-waiting-for-urlConnectionParams

Conversation

@hmatthieu

@hmatthieu hmatthieu commented Feb 22, 2025 •

Copy link
Copy Markdown
Contributor

🎯 Changes

Added a test case to ensure wsLink awaits urlConnectionParams before sending any messages. urlConnectionParams resolution is now handled at the wsConnection level. The wsClient can use the WebSocket once the connection parameters are sent.

βœ… Checklist

  • I have followed the steps listed in the Contributing guide.
  • If necessary, I have added documentation related to the changes made.
  • I have added or updated the tests related to the changes made.

Summary by CodeRabbit

  • Refactor

    • Streamlined the WebSocket connection initialization process by simplifying handshake operations and improving asynchronous handling for more reliable connection setups.
    • Removed unused properties and methods related to connection message building in the WebSocket client.
  • Tests

    • Introduced two new tests for asynchronous authentication to ensure that delayed credential retrieval integrates seamlessly with connection establishment and reconnections.

@hmatthieu
hmatthieu requested a review from a team as a code owner February 22, 2025 20:19
@railway-app

railway-app Bot commented Feb 22, 2025

Copy link
Copy Markdown

This PR was not deployed automatically as @hmatthieu does not have access to the Railway project.

In order to get automatic PR deploys, please add @hmatthieu to the project inside the project settings page.

@vercel

vercel Bot commented Feb 22, 2025 •

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for Git β†—οΈŽ

Name Status Preview Comments Updated (UTC)
next-prisma-starter βœ… Ready (Inspect) Visit Preview Feb 24, 2025 1:42pm
og-image βœ… Ready (Inspect) Visit Preview πŸ’¬ Add feedback Feb 24, 2025 1:42pm
1 Skipped Deployment
Name Status Preview Comments Updated (UTC)
www ⬜️ Ignored (Inspect) Visit Preview Feb 24, 2025 1:42pm

@pkg-pr-new

pkg-pr-new Bot commented Feb 22, 2025 •

Copy link
Copy Markdown

Open in Stackblitz

@trpc/client

npm i https://pkg.pr.new/trpc/trpc/@trpc/client@6547

@trpc/next

npm i https://pkg.pr.new/trpc/trpc/@trpc/next@6547

@trpc/server

npm i https://pkg.pr.new/trpc/trpc/@trpc/server@6547

@trpc/react-query

npm i https://pkg.pr.new/trpc/trpc/@trpc/react-query@6547

@trpc/tanstack-react-query

npm i https://pkg.pr.new/trpc/trpc/@trpc/tanstack-react-query@6547

@trpc/upgrade

npm i https://pkg.pr.new/trpc/trpc/@trpc/upgrade@6547

commit: 780f7a7

@coderabbitai

coderabbitai Bot commented Feb 22, 2025 •

Copy link
Copy Markdown
Contributor

Walkthrough

This update simplifies and refines the WebSocket connection process. In the WsClient module, an unused function and associated property related to connection messages have been removed, altering the initial message sending. The WsConnection module’s open method now resolves its promise with a then callback, reordering the setup of event listeners, including the ping listener, and conditionally sending a connection message when parameters are provided. Additionally, new asynchronous authentication tests have been added to simulate delayed token retrieval and validate the 'whoami' endpoint.

Changes

File(s) Change Summary
packages/client/.../wsClient.ts Removed the unused buildConnectionMessage function and connectionParams property from the WsClient class, eliminating the connection message send call in the open method.
packages/client/.../wsConnection.ts Refactored the open method: now resolves wsPromise via a then callback, sets up event listeners (ping, close) immediately upon obtaining the WebSocket instance, and conditionally sends a connection message.
packages/tests/.../websockets.test.ts Added new test cases for asynchronous authentication (with async auth and reconnect with async auth and pending subscriptions), utilizing a delayed response with the imported sleep function, and updated imports accordingly.

Possibly related PRs

Suggested labels

♻️ autoupdate

Suggested reviewers

  • KATT

Poem

Oh, I’m a rabbit, hopping through code,
Leaving behind unused bits on the road.
Streamlined paths where once chaos did roam,
With each line refined, I feel right at home.
A joyful twitch in every byte β€” hop to new code light!
πŸ‡βœ¨


πŸ“œ Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

πŸ“₯ Commits

Reviewing files that changed from the base of the PR and between 31b0544 and 4c477ec.

πŸ“’ Files selected for processing (1)
  • packages/tests/server/websockets.test.ts (3 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • packages/tests/server/websockets.test.ts
⏰ Context from checks skipped due to timeout of 90000ms (20)
  • GitHub Check: E2E-tests (fastify-server)
  • GitHub Check: E2E-tests (express-server)
  • GitHub Check: E2E-tests (express-minimal)
  • GitHub Check: e2e-legacy-node (next-prisma-todomvc, 20.x)
  • GitHub Check: E2E-tests (cloudflare-workers)
  • GitHub Check: e2e-legacy-node (next-prisma-todomvc, 18.x)
  • GitHub Check: E2E-tests (.test/ssg)
  • GitHub Check: e2e-legacy-node (next-prisma-websockets-starter, 20.x)
  • GitHub Check: E2E-tests (.test/internal-types-export)
  • GitHub Check: Release using pkg.pr.new
  • GitHub Check: Test a monorepo using built declaration files
  • GitHub Check: e2e-legacy-node (next-prisma-websockets-starter, 18.x)
  • GitHub Check: E2E-tests (.test/diagnostics-big-router)
  • GitHub Check: e2e-legacy-node (next-prisma-starter, 20.x)
  • GitHub Check: E2E-tests (.experimental/next-app-dir)
  • GitHub Check: e2e-legacy-node (next-prisma-starter, 18.x)
  • GitHub Check: E2E-tests (Bun) (bun, ubuntu-latest)
  • GitHub Check: E2E-tests (Deno) (deno-deploy)
  • GitHub Check: test
  • GitHub Check: Lint and auto-fix

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❀️ Share
πŸͺ§ Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR. (Beta)
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

πŸ“œ Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

πŸ“₯ Commits

Reviewing files that changed from the base of the PR and between 1eccc11 and fe0a8cc.

πŸ“’ Files selected for processing (3)
  • packages/client/src/links/wsLink/wsClient/wsClient.ts (1 hunks)
  • packages/client/src/links/wsLink/wsClient/wsConnection.ts (2 hunks)
  • packages/tests/server/websockets.test.ts (2 hunks)
πŸ”‡ Additional comments (2)
packages/client/src/links/wsLink/wsClient/wsClient.ts (1)

23-24: LGTM! Simplified imports.

The removal of buildConnectionMessage from imports is correct as the connection message handling has been moved to wsConnection.ts.

packages/tests/server/websockets.test.ts (1)

1766-1786: LGTM! Comprehensive test for async auth.

The test case effectively validates that:

  1. The WebSocket client waits for async connectionParams to resolve
  2. The connection is established with the correct auth token
  3. The whoami endpoint returns the expected user data

@TomKaltz

Copy link
Copy Markdown

@hmatthieu this may have introduced a regression, ping timeout/reconnect seems to have stopped working with this PR.

@hmatthieu

hmatthieu commented Feb 22, 2025 •

Copy link
Copy Markdown
Contributor Author

@hmatthieu this may have introduced a regression, ping timeout/reconnect seems to have stopped working with this PR.

@TomKaltz While the connectionParams async function resolves, reconnection will indeed not be active. But IMO that's fine β€” we don't want to retry if we haven't even finished our previous attempt, right?

Or are you talking about something else ?

@TomKaltz

Copy link
Copy Markdown

@hmatthieu this may have introduced a regression, ping timeout/reconnect seems to have stopped working with this PR.

Yes, upon a loss in network the ping never times out to close the current connection. When the network comes back up a new connection is forced but connectionParams are not sent on the new connection, resulting in authentication errors.

@hmatthieu

Copy link
Copy Markdown
Contributor Author

@TomKaltz

I was able to reproduce the issue. When reconnecting with a pending subscription, we don't wait for the connection parameters to be sent before restoring the subscriptions, resulting in an error.
image

I'll try to find an elegant fix

@TomKaltz

TomKaltz commented Feb 22, 2025 •

Copy link
Copy Markdown

My other concern is that the connection is not being forcefully closed upon ping timeout like before. Therefore user code is not notified of the loss in connection until the network comes back which is unintuitive.

@hmatthieu

Copy link
Copy Markdown
Contributor Author

@TomKaltz After further investigation:

Preliminary notes:

Previous wsLink behavior regarding keep-alive:
When wsLink didn't receive a pong from the server, it closed the connection and dispatched an onClose event. The app could react to this onClose event, but the connection was not automatically reopened.

After refactoring:
The behavior remains the same, but the connection now automatically reopens (which is IMO a bugfix). On my side, onClose followed by onOpen events are dispatched, allowing the app to react accordingly.

I couldn't reproduce your latest concern. I'll push my latest commit to this PR and would appreciate your feedback.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Nitpick comments (1)
packages/tests/server/websockets.test.ts (1)

1696-1698: Consider improving the never-resolving Promise implementation.

The empty arrow function in the Promise constructor could be made more explicit about its intended behavior.

-    iterable: t.procedure.subscription(async function* () {
-      await new Promise(() => {});
-    })
+    iterable: t.procedure.subscription(async function* () {
+      await new Promise((resolve) => {
+        // Intentionally never resolve to keep subscription active
+      });
+    })
🧰 Tools
πŸͺ› ESLint

[error] 1697-1697: Unexpected empty arrow function.

(@typescript-eslint/no-empty-function)

πŸ“œ Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

πŸ“₯ Commits

Reviewing files that changed from the base of the PR and between fe0a8cc and fe7c45a.

πŸ“’ Files selected for processing (3)
  • packages/client/src/links/wsLink/wsClient/wsClient.ts (2 hunks)
  • packages/client/src/links/wsLink/wsClient/wsConnection.ts (3 hunks)
  • packages/tests/server/websockets.test.ts (3 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • packages/client/src/links/wsLink/wsClient/wsClient.ts
  • packages/client/src/links/wsLink/wsClient/wsConnection.ts
🧰 Additional context used
πŸͺ› ESLint
packages/tests/server/websockets.test.ts

[error] 1697-1697: Unexpected empty arrow function.

(@typescript-eslint/no-empty-function)

⏰ Context from checks skipped due to timeout of 90000ms (20)
  • GitHub Check: E2E-tests (fastify-server)
  • GitHub Check: e2e-legacy-node (next-prisma-todomvc, 20.x)
  • GitHub Check: E2E-tests (express-server)
  • GitHub Check: e2e-legacy-node (next-prisma-todomvc, 18.x)
  • GitHub Check: E2E-tests (express-minimal)
  • GitHub Check: e2e-legacy-node (next-prisma-websockets-starter, 20.x)
  • GitHub Check: Release using pkg.pr.new
  • GitHub Check: E2E-tests (cloudflare-workers)
  • GitHub Check: e2e-legacy-node (next-prisma-websockets-starter, 18.x)
  • GitHub Check: E2E-tests (.test/ssg)
  • GitHub Check: Test a monorepo using built declaration files
  • GitHub Check: e2e-legacy-node (next-prisma-starter, 20.x)
  • GitHub Check: E2E-tests (.test/internal-types-export)
  • GitHub Check: e2e-legacy-node (next-prisma-starter, 18.x)
  • GitHub Check: E2E-tests (.test/diagnostics-big-router)
  • GitHub Check: E2E-tests (Bun) (bun, ubuntu-latest)
  • GitHub Check: E2E-tests (.experimental/next-app-dir)
  • GitHub Check: E2E-tests (Deno) (deno-deploy)
  • GitHub Check: test
  • GitHub Check: Lint and auto-fix
πŸ”‡ Additional comments (2)
packages/tests/server/websockets.test.ts (2)

1769-1789: LGTM! Well-structured async auth test.

The test effectively validates that the WebSocket client waits for async connection parameters before making requests. Good use of sleep to simulate real-world delays in token retrieval.


1791-1827: LGTM! Comprehensive reconnection test with async auth.

The test thoroughly validates that:

  1. Initial connection and subscription work with async auth
  2. Reconnection properly handles pending subscriptions
  3. Connection events are triggered in the correct order

Good use of mock functions to track the sequence of events.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

πŸ“œ Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

πŸ“₯ Commits

Reviewing files that changed from the base of the PR and between 16f8f1b and 31b0544.

πŸ“’ Files selected for processing (1)
  • packages/tests/server/websockets.test.ts (3 hunks)
🧰 Additional context used
πŸͺ› Biome (1.9.4)
packages/tests/server/websockets.test.ts

[error] 1696-1698: This generator function doesn't contain yield.

(lint/correctness/useYield)

⏰ Context from checks skipped due to timeout of 90000ms (19)
  • GitHub Check: E2E-tests (fastify-server)
  • GitHub Check: E2E-tests (express-server)
  • GitHub Check: E2E-tests (express-minimal)
  • GitHub Check: E2E-tests (cloudflare-workers)
  • GitHub Check: E2E-tests (.test/ssg)
  • GitHub Check: E2E-tests (.test/internal-types-export)
  • GitHub Check: e2e-legacy-node (next-prisma-todomvc, 20.x)
  • GitHub Check: Release using pkg.pr.new
  • GitHub Check: e2e-legacy-node (next-prisma-todomvc, 18.x)
  • GitHub Check: Test a monorepo using built declaration files
  • GitHub Check: E2E-tests (.test/diagnostics-big-router)
  • GitHub Check: e2e-legacy-node (next-prisma-websockets-starter, 20.x)
  • GitHub Check: E2E-tests (.experimental/next-app-dir)
  • GitHub Check: e2e-legacy-node (next-prisma-websockets-starter, 18.x)
  • GitHub Check: E2E-tests (Bun) (bun, ubuntu-latest)
  • GitHub Check: e2e-legacy-node (next-prisma-starter, 20.x)
  • GitHub Check: e2e-legacy-node (next-prisma-starter, 18.x)
  • GitHub Check: E2E-tests (Deno) (deno-deploy)
  • GitHub Check: test
πŸ”‡ Additional comments (3)
packages/tests/server/websockets.test.ts (3)

1769-1789: LGTM! Well-structured test for async authentication.

The test effectively validates that the WebSocket client properly awaits async connection parameters before proceeding with queries.


1791-1827: LGTM! Comprehensive test for reconnection with async auth.

The test thoroughly verifies that:

  1. The connection opens correctly with async auth
  2. Subscriptions start properly
  3. Reconnection works without duplicating subscriptions
  4. The WebSocket client maintains the expected state

16-19:

Details

βœ… Verification successful

Verify the use of unstable core imports.

The code imports from @trpc/server/unstable-core-do-not-import. This path suggests the module is not intended for production use. Since this is a test file, it's acceptable, but we should verify if there's a stable alternative available.


🌐 Web query:

Is there a stable alternative to @trpc/server/unstable-core-do-not-import in tRPC?

πŸ’‘ Result:

tRPC has been actively working to reduce reliance on @trpc/server/unstable-core-do-not-import by migrating functionality to stable entry points[1][9]. While there isn't a direct 1:1 replacement for all unstable exports yet, here are the current alternatives:

Stable Alternatives:

  • Use standard imports from @trpc/server instead of unstable paths[1][3]
  • Leverage official packages like:
    • @trpc/client
    • @trpc/react-query
    • @trpc/next[1]
  • For plugins, use the new @trpc/server/plugin entrypoint (recently added)[1][9]

Key Recommendations:

  1. Avoid direct imports from unstable-core-do-not-import unless absolutely necessary[3][8]
  2. Ensure all @trpc/* packages share matching versions[3]
  3. Use TypeScript β‰₯5.6.2 with strict mode enabled[3]
  4. Monitor official releases for newly stabilized APIs[9]

The tRPC team maintains strict semver compliance for non-unstable exports and considers type changes as breaking changes[3]. Features marked unstable_ remain production-safe but may see minor API adjustments, while experimental_ features carry higher instability risks[3].

For developers encountering type errors when upgrading (like ReadableStream issues), adding "DOM" to tsconfig.json's lib array often resolves them[5]. When migrating large codebases, consider automated API change detection through OpenAPI specifications[7].

Citations:


Usage of Unstable Core Imports Confirmed

The import from @trpc/server/unstable-core-do-not-import in packages/tests/server/websockets.test.ts is acceptable in this test context. The tRPC documentation confirms that while a complete 1:1 stable alternative for all unstable exports isn’t yet available, stable imports (e.g., from @trpc/server) are being progressively introduced. For now, using these unstable exports in tests is fine, but please consider migrating to the stable alternatives as they become fully supported in future releases.

@TomKaltz

Copy link
Copy Markdown

I can confirm that proper reconnect upon network restore is now working. What is not working optimally IMHO is that the original connection is not forcefully closed when a keepaline ping times out. Due to this, the connection just hangs open until the network connection returns, then the original connection is finally closed and a new one is opened. I'm using chrome devtools network tab "offline" throttling to simulate a dropped connection.

@KATT
KATT enabled auto-merge (squash) February 24, 2025 09:37
@github-actions

Copy link
Copy Markdown
Contributor

This pull request has been locked because we are very unlikely to see comments on closed issues. If you think, this PR is still necessary, create a new one with the same branch. Thank you.

@github-actions github-actions Bot locked as resolved and limited conversation to collaborators Feb 25, 2025

This branch was successfully deployed

5 active (1 outdated) deployments
Preview – next-prisma-starter β€” 780f7a75 Deployed Feb 24, 2025 by vercel[bot]
Preview – examples-todomvc β€” 780f7a75 Deployed Feb 24, 2025 by vercel[bot]
Preview – trpc-next-app-dir β€” 780f7a75 Deployed Feb 24, 2025 by vercel[bot]
Preview – og-image β€” 780f7a75 Deployed Feb 24, 2025 by vercel[bot]
Preview – www β€” c36b1212 Deployed Feb 24, 2025 by vercel[bot]
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants