Repository navigation
Conversation
|
@hmatthieu is attempting to deploy a commit to the trpc Team on Vercel. A member of the Team first needs to authorize it. |
|
The latest updates on your projects. Learn more about Vercel for Git ↗︎
|
@trpc/client
@trpc/next
@trpc/react-query
@trpc/server
@trpc/upgrade
@trpc/tanstack-react-query
commit: |
Remove index.ts files in favor of explicit names
Rename pending to outgoing; active to pending
There was a problem hiding this comment.
Actionable comments posted: 1
♻️ Duplicate comments (8)
packages/client/src/links/wsLink/wsClient/wsConnection.ts (2)
181-185:⚠️ Potential issuePrevent race conditions in connection attempts.
The
openPromiseis nullified in thefinallyblock even if the connection fails, which could allow multiple simultaneous connection attempts.try { await this.openPromise; + this.openPromise = null; } finally { - this.openPromise = null; + // Only clean up resources here }
192-198:⚠️ Potential issueClean up event listeners on close.
Event listeners should be removed when closing the connection to prevent potential memory leaks, even if the WebSocket instance won't be reused.
public async close() { try { await this.openPromise; } finally { + if (this.ws) { + // Remove all event listeners + this.ws.removeEventListener('message', this.ws.onmessage); + this.ws.removeEventListener('close', this.ws.onclose); + this.ws.removeEventListener('error', this.ws.onerror); + this.ws.removeEventListener('open', this.ws.onopen); this.ws.close(); + } } }packages/client/src/links/wsLink/wsClient/requestManager.ts (3)
3-6:⚠️ Potential issueAvoid importing from unstable core.
Importing from
@trpc/server/unstable-core-do-not-importmay lead to compatibility issues as it's intended for internal use.Consider using the stable public API:
-import type { - TRPCClientOutgoingMessage, - TRPCResponseMessage, -} from '@trpc/server/unstable-core-do-not-import'; +import type { TRPCClientOutgoingMessage, TRPCResponseMessage } from '@trpc/server/rpc';
58-83:⚠️ Potential issueHandle potential race conditions in request lifecycle.
The cleanup function returned by
registermay cause duplicate completions if the request was already completed.Consider this safer implementation:
return () => { + const request = this.getPendingRequest(message.id); + if (!request) return; + this.delete(message.id); callbacks.complete(); resolve(); };
105-113:⚠️ Potential issueHandle edge cases in flush method.
The flush method should handle cleanup of existing pending requests to prevent memory leaks.
Consider this safer implementation:
public flush() { + // Clean up existing pending requests to prevent memory leaks + for (const id in this.pendingRequests) { + this.delete(id); + } + const requests = this.outgoingRequests; this.outgoingRequests = []; for (const request of requests) { this.pendingRequests[request.id] = request; } return requests; }packages/client/src/links/wsLink/wsClient/wsClient.ts (3)
408-411:⚠️ Potential issueReplace instanceof Array with Array.isArray().
Using
instanceof Arrayis unreliable as it returns false for array-like objects and arrays from other execution contexts.Apply this fix:
const messages = - messageOrMessages instanceof Array + Array.isArray(messageOrMessages) ? messageOrMessages : [messageOrMessages];🧰 Tools
🪛 Biome (1.9.4)
[error] 409-409: Use Array.isArray() instead of instanceof Array.
instanceof Array returns false for array-like objects and arrays from other execution contexts.
Unsafe fix: Use Array.isArray() instead.(lint/suspicious/useIsArray)
431-433:⚠️ Potential issueHandle potential race condition in request management.
There's a potential race condition between checking
hasOutgoingRequests()andflush()- another request could be added or removed between these calls.Consider this safer implementation:
- if (!this.requestManager.hasOutgoingRequests()) return; - - this.send(this.requestManager.flush().map(({ message }) => message)); + const outgoingRequests = this.requestManager.flush(); + if (outgoingRequests.length > 0) { + this.send(outgoingRequests.map(({ message }) => message)); + }
294-322:⚠️ Potential issueAvoid async event listener.
Using an async function in the event listener could lead to error handling issues.
Apply this fix:
- ws.addEventListener('open', () => { + ws.addEventListener('open', () => { run(async () => { if (this.lazyMode) { this.inactivityTimeout.start(); } if (this.connectionParams) { ws.send(await buildConnectionMessage(this.connectionParams)); } this.callbacks.onOpen?.(); this.connectionState.next({ type: 'state', state: 'pending', error: null, }); const messages = this.requestManager .getPendingRequests() .map(({ message }) => message); if (messages.length) { ws.send(JSON.stringify(messages)); } }).catch(error => { ws.close(3000); handleCloseOrError(error); }) });
🧹 Nitpick comments (4)
packages/client/src/links/wsLink/wsClient/wsConnection.ts (3)
46-85: Add error handling for ping message sending.While the ping-pong mechanism is well-implemented, consider adding error handling for the
sendoperation to gracefully handle network issues.function start() { pingTimeout = setTimeout(() => { - ws.send('PING'); + try { + ws.send('PING'); + } catch (error) { + // If send fails, close the connection as it's likely in a bad state + ws.close(); + } pongTimeout = setTimeout(() => { ws.close(); }, pongTimeoutMs); }, intervalMs); }
103-118: Enhance type safety for WebSocket ponyfill.Consider using a more specific type for the WebSocket ponyfill to ensure type safety and better IDE support.
- private readonly WebSocketPonyfill: typeof WebSocket; + private readonly WebSocketPonyfill: { + new (url: string | URL): WebSocket; + readonly CONNECTING: 0; + readonly OPEN: 1; + readonly CLOSING: 2; + readonly CLOSED: 3; + };
204-230: Improve type safety in state representation.Consider using proper TypeScript types instead of type assertions for better type safety and maintainability.
+type ConnectionState = 'open' | 'closed' | 'connecting'; +interface ConnectionInfo { + id: number; + state: ConnectionState; + ws: WebSocket; +} -export function backwardCompatibility(connection: WsConnection) { +export function backwardCompatibility(connection: WsConnection): ConnectionInfo | null { if (connection.isOpen()) { return { id: connection.id, state: 'open', ws: connection.ws, - } as const; + }; } // ... rest of the function }packages/client/src/links/wsLink/wsClient/utils.ts (1)
56-66: Consider a safer alternative to non-null assertions.The function uses non-null assertions (
!) which can be unsafe. Consider using a closure to avoid them.Apply this diff for a safer implementation:
export function withResolvers<T>() { - let resolve: (value: T | PromiseLike<T>) => void; - let reject: (reason?: any) => void; + let resolve!: (value: T | PromiseLike<T>) => void; + let reject!: (reason?: any) => void; const promise = new Promise<T>((res, rej) => { resolve = res; reject = rej; }); - // eslint-disable-next-line @typescript-eslint/no-non-null-assertion - return { promise, resolve: resolve!, reject: reject! }; + return { promise, resolve, reject }; }
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (15)
examples/fastify-server/src/client/index.ts(1 hunks)examples/standalone-server/src/client.ts(1 hunks)packages/client/package.json(1 hunks)packages/client/rollup.config.ts(1 hunks)packages/client/src/links.ts(1 hunks)packages/client/src/links/wsLink.ts(0 hunks)packages/client/src/links/wsLink/createWsClient.ts(1 hunks)packages/client/src/links/wsLink/wsClient/options.ts(1 hunks)packages/client/src/links/wsLink/wsClient/requestManager.ts(1 hunks)packages/client/src/links/wsLink/wsClient/utils.ts(1 hunks)packages/client/src/links/wsLink/wsClient/wsClient.ts(1 hunks)packages/client/src/links/wsLink/wsClient/wsConnection.ts(1 hunks)packages/client/src/links/wsLink/wsLink.ts(1 hunks)packages/tests/server/___testHelpers.ts(2 hunks)packages/tests/server/websockets.test.ts(8 hunks)
💤 Files with no reviewable changes (1)
- packages/client/src/links/wsLink.ts
🚧 Files skipped from review as they are similar to previous changes (8)
- examples/fastify-server/src/client/index.ts
- examples/standalone-server/src/client.ts
- packages/client/rollup.config.ts
- packages/client/package.json
- packages/client/src/links.ts
- packages/client/src/links/wsLink/createWsClient.ts
- packages/client/src/links/wsLink/wsLink.ts
- packages/client/src/links/wsLink/wsClient/options.ts
🧰 Additional context used
🪛 Biome (1.9.4)
packages/client/src/links/wsLink/wsClient/wsClient.ts
[error] 409-409: Use Array.isArray() instead of instanceof Array.
instanceof Array returns false for array-like objects and arrays from other execution contexts.
Unsafe fix: Use Array.isArray() instead.
(lint/suspicious/useIsArray)
⏰ 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: Test a monorepo using built declaration files
- GitHub Check: e2e-legacy-node (next-prisma-todomvc, 18.x)
- GitHub Check: E2E-tests (.test/ssg)
- GitHub Check: Release using pkg.pr.new
- GitHub Check: E2E-tests (.test/internal-types-export)
- GitHub Check: e2e-legacy-node (next-prisma-websockets-starter, 20.x)
- GitHub Check: E2E-tests (.test/diagnostics-big-router)
- GitHub Check: e2e-legacy-node (next-prisma-websockets-starter, 18.x)
- GitHub Check: E2E-tests (.experimental/next-app-dir)
- GitHub Check: e2e-legacy-node (next-prisma-starter, 20.x)
- GitHub Check: E2E-tests (Deno) (deno-deploy)
- GitHub Check: e2e-legacy-node (next-prisma-starter, 18.x)
- GitHub Check: E2E-tests (Bun) (bun, ubuntu-latest)
- GitHub Check: test
- GitHub Check: Lint and auto-fix
🔇 Additional comments (8)
packages/client/src/links/wsLink/wsClient/wsConnection.ts (1)
10-20: LGTM! Well-implemented async WebSocket opening.The implementation properly handles the asynchronous nature of WebSocket connections with appropriate error handling and event listener cleanup.
packages/client/src/links/wsLink/wsClient/utils.ts (4)
11-19: LGTM!The error class is well-implemented with proper error inheritance and prototype chain setup.
25-53: Extract common timeout logic to reduce code duplication.The
reset()andstart()methods have duplicate code for clearing and setting timeout.Apply this diff to extract the common logic:
export class ResettableTimeout { private timeout: ReturnType<typeof setTimeout> | undefined; constructor( private readonly onTimeout: () => void, private readonly timeoutMs: number, ) {} + private setTimer() { + clearTimeout(this.timeout); + this.timeout = setTimeout(this.onTimeout, this.timeoutMs); + } public reset() { if (!this.timeout) return; - clearTimeout(this.timeout); - this.timeout = setTimeout(this.onTimeout, this.timeoutMs); + this.setTimer(); } public start() { - clearTimeout(this.timeout); - this.timeout = setTimeout(this.onTimeout, this.timeoutMs); + this.setTimer(); } public stop() { clearTimeout(this.timeout); this.timeout = undefined; } }
73-83: LGTM!The URL preparation logic is well-implemented with proper handling of existing query parameters.
85-94: LGTM!The connection message building logic is well-implemented with proper JSON serialization.
packages/tests/server/___testHelpers.ts (1)
95-95: LGTM!The changes improve server management by:
- Allowing server restart through reassignable variables
- Adding proper state checks in the
openmethod- Using getters to ensure latest values are returned
Also applies to: 98-100, 108-108, 148-155, 163-165, 167-169
packages/tests/server/websockets.test.ts (2)
156-156: LGTM! Fixed retry delay improves test reliability.Using a fixed retry delay of 50ms makes the test more deterministic and less prone to flakiness.
1928-2085: LGTM! Comprehensive test coverage for edge cases.The new test cases effectively cover important scenarios:
- Concurrent operations with active subscriptions and queries
- Connection failure handling with both lazy and immediate connections
- Proper cleanup and state management
The tests are well-structured and provide good coverage of the WebSocket client's resilience.
| await vi.advanceTimersByTimeAsync(1); | ||
| await new Promise((resolve) => { | ||
| ctx.wsClient.connection!.ws!.addEventListener('open', resolve); | ||
| ctx.wsClient.connection!.ws.addEventListener('open', resolve); |
There was a problem hiding this comment.
🛠️ Refactor suggestion
Replace non-null assertions with explicit null checks.
Using non-null assertions (!) can hide potential runtime errors. Consider adding explicit null checks.
Apply this diff to add proper null checks:
- ctx.wsClient.connection!.ws.addEventListener('open', resolve);
+ if (!ctx.wsClient.connection) {
+ throw new Error('WebSocket connection not initialized');
+ }
+ ctx.wsClient.connection.ws.addEventListener('open', resolve);Also applies to lines 1601, 1643, and 1647.
Also applies to: 1601-1601, 1643-1643, 1647-1647
There was a problem hiding this comment.
Actionable comments posted: 1
♻️ Duplicate comments (3)
packages/client/src/links/wsLink/wsClient/wsClient.ts (3)
69-78:⚠️ Potential issueFix potential race condition in inactivity timeout.
There's a race condition between checking for pending/outgoing requests and closing the connection. Another request could be added between these checks and the close call.
Consider this improvement:
this.inactivityTimeout = new ResettableTimeout(() => { - if ( - this.requestManager.hasOutgoingRequests() || - this.requestManager.hasPendingRequests() - ) { - this.inactivityTimeout.reset(); - return; - } - - this.close().catch(() => null); + const hasRequests = + this.requestManager.hasOutgoingRequests() || + this.requestManager.hasPendingRequests(); + + if (!hasRequests) { + this.close().catch(() => null); + } else { + this.inactivityTimeout.reset(); + } }, lazyOptions.closeMs);
300-302:⚠️ Potential issueImprove error handling for connection parameters.
The error from connection parameters is not properly propagated to the connection state.
Consider this improvement:
if (this.connectionParams) { try { ws.send(await buildConnectionMessage(this.connectionParams)); } catch (error) { ws.close(3000); + this.connectionState.next({ + type: 'state', + state: 'connecting', + error: TRPCClientError.from(error), + }); handleCloseOrError(error); return; } }
408-411:⚠️ Potential issueReplace instanceof Array with Array.isArray().
Using
instanceof Arrayis unreliable as it returns false for array-like objects and arrays from other execution contexts.Apply this fix:
const messages = - messageOrMessages instanceof Array + Array.isArray(messageOrMessages) ? messageOrMessages : [messageOrMessages];🧰 Tools
🪛 Biome (1.9.4)
[error] 409-409: Use Array.isArray() instead of instanceof Array.
instanceof Array returns false for array-like objects and arrays from other execution contexts.
Unsafe fix: Use Array.isArray() instead.(lint/suspicious/useIsArray)
🧹 Nitpick comments (2)
packages/client/src/links/wsLink/wsClient/wsClient.ts (2)
186-239: Enhance error handling in request method.Consider adding timeout handling and more detailed error messages for different failure scenarios.
Consider these improvements:
public request({ op: { id, type, path, input, signal }, transformer, lastEventId, + timeout?: number, }: { op: Pick<Operation, 'id' | 'type' | 'path' | 'input' | 'signal'>; transformer: CombinedDataTransformer; lastEventId?: string; + timeout?: number; }) { return observable< OperationResultEnvelope<unknown, TRPCClientError<AnyTRPCRouter>>, TRPCClientError<AnyTRPCRouter> >((observer) => { + const timeoutId = timeout && setTimeout(() => { + observer.error( + TRPCClientError.from( + new Error(`Request timeout after ${timeout}ms`), + ), + ); + abort(); + }, timeout); + const abort = this.batchSend( // ... existing code ... ); return () => { + timeoutId && clearTimeout(timeoutId); abort(); // ... existing code ... }; }); }
259-270: Add logging for reconnection attempts.Adding logs would help with debugging connection issues in production.
Consider this improvement:
const tryReconnect = async (attemptIndex: number) => { + console.debug( + `Attempting to reconnect (attempt ${attemptIndex + 1}, delay: ${ + this.reconnectRetryDelay(attemptIndex) + }ms)`, + ); try { await sleep(this.reconnectRetryDelay(attemptIndex)); if (this.allowReconnect) { await this.activeConnection.close(); await this.activeConnection.open(); + console.debug('Reconnection successful'); } this.reconnecting = null; } catch (error) { + console.warn( + `Reconnection attempt ${attemptIndex + 1} failed:`, + error, + ); await tryReconnect(attemptIndex + 1); } };
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (1)
packages/client/src/links/wsLink/wsClient/wsClient.ts(1 hunks)
🧰 Additional context used
🪛 Biome (1.9.4)
packages/client/src/links/wsLink/wsClient/wsClient.ts
[error] 409-409: Use Array.isArray() instead of instanceof Array.
instanceof Array returns false for array-like objects and arrays from other execution contexts.
Unsafe fix: Use Array.isArray() instead.
(lint/suspicious/useIsArray)
⏰ Context from checks skipped due to timeout of 90000ms (3)
- GitHub Check: build
- GitHub Check: test
- GitHub Check: Lint and auto-fix
🔇 Additional comments (1)
packages/client/src/links/wsLink/wsClient/wsClient.ts (1)
145-174: LGTM! Well-structured connection cleanup.The close method properly handles:
- Stopping reconnection attempts
- Completing subscriptions
- Handling pending requests
- Cleaning up the connection state
| if (!this.lazyMode) { | ||
| this.open().catch(() => null); | ||
| } |
There was a problem hiding this comment.
🛠️ Refactor suggestion
Improve error handling in constructor.
The error from the initial connection attempt is silently ignored, which could mask important initialization issues.
Consider this improvement:
if (!this.lazyMode) {
- this.open().catch(() => null);
+ this.open().catch((error) => {
+ this.callbacks.onError?.(new Event('error'));
+ console.error('Failed to initialize WebSocket connection:', error);
+ });
}📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| if (!this.lazyMode) { | |
| this.open().catch(() => null); | |
| } | |
| if (!this.lazyMode) { | |
| this.open().catch((error) => { | |
| this.callbacks.onError?.(new Event('error')); | |
| console.error('Failed to initialize WebSocket connection:', error); | |
| }); | |
| } |
|
@hmatthieu with the new wsLink in this pull request I'm now having an issue where the connectionParams message is not the first message sent over the wire. I use it to send authentication token to the server but now my initial subscriptions on the frontend are failing because the subscription messages are sent before the connectionParams message upon connection. |
Could you share a snippet with your connectionParams please ? |
|
@hmatthieu > Could you share a snippet with your connectionParams please ? |
I'll look into it this week |
|
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. |


Closes #6109
WebSocket Implementation Refactoring
This PR addresses #6109 by completely refactoring the WebSocket implementation to improve maintainability. The new implementation maintains all existing functionality while providing a cleaner and more modular architecture.
🔄 Architecture Improvements
Split the monolithic WebSocket client into focused, single-responsibility modules:
wsLink: Streamlined to handle only connection state observabilityWsClient: Acts as the high-level coordinator between modulesWsConnection: Provides low-level WebSocket controlRequestManager: Dedicated to managing tRPC request lifecyclesReconnectManager: Handles reconnection logic and backoff strategiesPingPong: Implements connection health monitoring✅ Checklist
Summary by CodeRabbit
New Features
RequestManagerclass for better lifecycle management of WebSocket requests.Bug Fixes
Refactor
Tests