Skip to content

chore(client): refactor & undeprecate wsLink - #6223

Merged
KATT merged 25 commits into
trpc:nextfrom
hmatthieu:refacto/6109-wsLink
Feb 18, 2025
Merged

KATT merged 25 commits into
trpc:nextfrom
hmatthieu:refacto/6109-wsLink

Conversation

@hmatthieu

@hmatthieu hmatthieu commented Nov 12, 2024 •

Copy link
Copy Markdown
Contributor

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 observability
  • WsClient: Acts as the high-level coordinator between modules
  • WsConnection: Provides low-level WebSocket control
  • RequestManager: Dedicated to managing tRPC request lifecycles
  • ReconnectManager: Handles reconnection logic and backoff strategies
  • PingPong: Implements connection health monitoring

✅ 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

  • New Features

    • Improved real-time communication with advanced connection management, including lazy initialization, keep-alive support, and robust error handling.
    • Introduced a new WebSocket client class with enhanced features for managing TRPC operations.
    • Added a new function for creating a WebSocket client with customizable options.
    • Implemented a comprehensive WebSocket connection management system with ping-pong mechanisms.
    • Enhanced the RequestManager class for better lifecycle management of WebSocket requests.
    • Added new utility functions for error handling and connection message construction.
    • Updated the WebSocket link functionality for improved communication between client and server.
  • Bug Fixes

    • Ensured that WebSocket connections now close gracefully by handling closures asynchronously, reducing potential disruptions.
  • Refactor

    • Streamlined the internal structure of WebSocket modules to enhance maintainability and simplify configuration.
    • Modified the management of WebSocket server handlers for improved flexibility.
    • Updated export paths and organization for better module structure.
  • Tests

    • Expanded coverage with new scenarios that simulate connection failures and verify active subscriptions for improved stability.

@vercel

vercel Bot commented Nov 12, 2024

Copy link
Copy Markdown

@hmatthieu is attempting to deploy a commit to the trpc Team on Vercel.

A member of the Team first needs to authorize it.

@vercel

vercel Bot commented Nov 12, 2024 •

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for Git ↗︎

Name Status Preview Comments Updated (UTC)
og-image ✅ Ready (Inspect) Visit Preview 💬 Add feedback Feb 18, 2025 9:34am
www ✅ Ready (Inspect) Visit Preview 💬 Add feedback Feb 18, 2025 9:34am

@pkg-pr-new

pkg-pr-new Bot commented Nov 17, 2024 •

Copy link
Copy Markdown

Open in Stackblitz

@trpc/client

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

@trpc/next

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

@trpc/react-query

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

@trpc/server

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

@trpc/upgrade

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

@trpc/tanstack-react-query

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

commit: cd20c52

@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

♻️ Duplicate comments (8)
packages/client/src/links/wsLink/wsClient/wsConnection.ts (2)

181-185: ⚠️ Potential issue

Prevent race conditions in connection attempts.

The openPromise is nullified in the finally block 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 issue

Clean 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 issue

Avoid importing from unstable core.

Importing from @trpc/server/unstable-core-do-not-import may 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 issue

Handle potential race conditions in request lifecycle.

The cleanup function returned by register may 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 issue

Handle 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 issue

Replace instanceof Array with Array.isArray().

Using instanceof Array is 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 issue

Handle potential race condition in request management.

There's a potential race condition between checking hasOutgoingRequests() and flush() - 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 issue

Avoid 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 send operation 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

📥 Commits

Reviewing files that changed from the base of the PR and between 284ccde and 08882b2.

📒 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() and start() 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 open method
  • 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:

  1. Concurrent operations with active subscriptions and queries
  2. Connection failure handling with both lazy and immediate connections
  3. 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);

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.

🛠️ 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

@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

♻️ Duplicate comments (3)
packages/client/src/links/wsLink/wsClient/wsClient.ts (3)

69-78: ⚠️ Potential issue

Fix 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 issue

Improve 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 issue

Replace instanceof Array with Array.isArray().

Using instanceof Array is 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

📥 Commits

Reviewing files that changed from the base of the PR and between 08882b2 and d93fc82.

📒 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

Comment on lines +109 to +111
if (!this.lazyMode) {
this.open().catch(() => null);
}

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.

🛠️ 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.

Suggested change
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);
});
}

@TomKaltz

Copy link
Copy Markdown

@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.

@hmatthieu

Copy link
Copy Markdown
Contributor Author

@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 ?

@TomKaltz

Copy link
Copy Markdown

@hmatthieu > Could you share a snippet with your connectionParams please ?

    wsClient = createWSClient({
      url: `${window.location.protocol === "https:" ? "wss" : "ws"}://${window.location.host}/api/trpc-ws`,
      retryDelayMs: (retryCount) =>
        Math.max(200 * Math.pow(2, retryCount), 2000),
      WebSocket: WebSocket,
      async connectionParams() {
        const user = await useCurrentUser();
        const token = await user.value?.getIdToken(true);
        return token ? { Authorization: `Bearer ${token}` } : {};
      },
      keepAlive: {
        enabled: true,
        intervalMs: 1000,
        pongTimeoutMs: 4000,
      },
      onClose(cause) {
        console.log("WebSocket closed:", cause);
      },
      onOpen() {
        console.log("WebSocket opened");
      },
      onError(error) {
        console.error("WebSocket error:", error);
      },
    });

The order of messages sent out...
Screenshot 2025-02-18 at 14 17 20

@hmatthieu

Copy link
Copy Markdown
Contributor Author

@hmatthieu > Could you share a snippet with your connectionParams please ?

    wsClient = createWSClient({
      url: `${window.location.protocol === "https:" ? "wss" : "ws"}://${window.location.host}/api/trpc-ws`,
      retryDelayMs: (retryCount) =>
        Math.max(200 * Math.pow(2, retryCount), 2000),
      WebSocket: WebSocket,
      async connectionParams() {
        const user = await useCurrentUser();
        const token = await user.value?.getIdToken(true);
        return token ? { Authorization: `Bearer ${token}` } : {};
      },
      keepAlive: {
        enabled: true,
        intervalMs: 1000,
        pongTimeoutMs: 4000,
      },
      onClose(cause) {
        console.log("WebSocket closed:", cause);
      },
      onOpen() {
        console.log("WebSocket opened");
      },
      onError(error) {
        console.error("WebSocket error:", error);
      },
    });

The order of messages sent out... Screenshot 2025-02-18 at 14 17 20

I'll look into it this week

@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.

@hmatthieu

Copy link
Copy Markdown
Contributor Author

@TomKaltz I added a test case + a fix #6547

This branch was successfully deployed

3 active (1 outdated) deployments
Preview – www — cd20c520 Deployed Feb 18, 2025 by vercel[bot]
Preview – trpc-next-app-dir — cd20c520 Deployed Feb 18, 2025 by vercel[bot]
Preview – og-image — ac657ec9 Deployed Dec 4, 2024 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.

feat: Maintainers wanted for wsLink

3 participants