Skip to content
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

Add connection retry for web lib #1

Merged
merged 1 commit into from
Mar 9, 2025
Merged

Conversation

arjunkomath
Copy link
Owner

@arjunkomath arjunkomath commented Mar 9, 2025

Summary by CodeRabbit

  • New Features

    • Enhanced network connection management now offers automatic reconnection with customizable retry settings. This update improves overall stability and delivers a smoother experience during network fluctuations.
  • Chores

    • The build and deployment processes have been refined to ensure that the latest enhancements are consistently delivered, streamlining our release cycle and contributing to a more reliable update experience.

Copy link

coderabbitai bot commented Mar 9, 2025

Walkthrough

The changes update two files. In packages/web/package.json, the "files" array is reformatted into a single line, a new prepublishOnly script is added to run the build prior to publishing, and the dependency for @types/node is removed. In packages/web/src/index.ts, the TurboWire class is enhanced with additional properties and methods to incorporate retry logic and improved error handling for WebSocket connections. New optional parameters in TurboWireOptions allow customization of reconnection behavior.

Changes

File Path Change Summary
packages/web/package.json Reformatted "files" array to a single line; added "prepublishOnly": "npm run build" script; removed @types/node from devDependencies.
packages/web/src/index.ts Enhanced TurboWire class: added optional maxRetries and retryInterval to options; introduced new private properties and methods for retry logic; updated event handlers for connection management.

Sequence Diagram(s)

sequenceDiagram
  participant TW as TurboWire
  participant WS as WebSocket Server
  TW->>WS: establishConnection()
  Note right of TW: Set onMessage & onError callbacks
  WS-->>TW: onopen (connection established)
  TW->>TW: Reset retryCount & assign messageCallback
  WS-->>TW: onmessage (handle incoming message)
  WS-->>TW: onclose (connection closed)
  alt Unclean disconnect & retryCount < maxRetries
    TW->>TW: Increment retryCount and schedule reconnect
    TW->>WS: Re-attempt connection
  else Clean disconnect or max retries reached
    TW->>TW: Invoke disconnect logic, clear retry timeout
  end
Loading

Poem

I'm a rabbit with code so spry,
Hopping through webs that never die,
With retries and callbacks in my burrow so deep,
I guard each connection while others sleep.
Prepublish scripts and builds make me beam—
Leaping through code like a joyous dream!

✨ Finishing Touches
  • 📝 Generate Docstrings

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

Copy link

@coderabbitai coderabbitai bot left a comment

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 (3)
packages/web/src/index.ts (3)

28-29: Constructor defaults for retry logic.

Providing default values of maxRetries = 10 and retryInterval = 3000 is sensible. Consider mentioning this default behavior in the README or doc comments so users know what to expect if they omit these fields.


42-43: Storing callbacks in private properties.

This is a clean approach for reusability in different event handlers. However, if the user calls connect() multiple times without a preceding disconnect(), it might cause overlapping WebSocket connections. Documenting or guarding against this scenario could make the API more robust.


88-98: Reconnection logic on unclean disconnections.

The retry approach is straightforward. However, consider introducing exponential backoff or randomized jitter to avoid tight reconnection loops under severe network instability. This helps reduce server load and collisions from repeated identical intervals.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 1cb52e4 and 798f855.

⛔ Files ignored due to path filters (1)
  • packages/web/pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
📒 Files selected for processing (2)
  • packages/web/package.json (1 hunks)
  • packages/web/src/index.ts (5 hunks)
🔇 Additional comments (13)
packages/web/src/index.ts (10)

3-4: Optional fields added to TurboWireOptions.

These new fields are consistent with the intended retry logic. Consider adding a doc comment explaining the default values to ensure clarity for users reading the type definition.


11-12: Private callbacks for message and error.

Defining separate callbacks is a straightforward way to handle different event types. The naming is clear and consistent with the rest of the class.


45-45: Initial WebSocket establishment.

Calling this.establishConnection() at connect time centralizes your connection logic. This is a good pattern for clarity and maintainability.


48-48: Refactored method for connection flow.

Extracting the connection flow into establishConnection() keeps connect() concise and easy to read.


50-50: Verbose logging of connection attempts.

Having a log statement here is useful in debug mode; it helps developers pinpoint connection attempts when analyzing logs.


59-59: Invoking error callback on WebSocket error.

Delegating to this.errorCallback is a clean way to let higher layers handle errors without polluting core logic. This separation of concerns is good practice.


66-66: Resetting retry count on successful connection.

This ensures subsequent disconnections start with a clean slate for retry logic. This is a sensible approach.


73-73: Invoking message callback for incoming messages.

Forwarding the raw data to messageCallback is a standard pattern for event-driven design. It keeps the receiving mechanism agnostic to any message parsing.


121-124: Clearing the retry timeout and resetting the retry count on disconnect.

This ensures no reconnection attempts occur after a deliberate disconnect. The logic neatly prevents lingering timeouts.

Also applies to: 134-134


14-17:

❓ Verification inconclusive

New private fields for retry logic.

Defining these fields is essential for reconnection behavior. However, ensure you handle invalid user input (e.g., negative maxRetries or retryInterval). An explicit check with a reasonable fallback could prevent edge cases.

Would you like to confirm if any external code passes invalid values for these properties? We can do that by scanning the codebase for calls into the constructor:


🏁 Script executed:

#!/bin/bash
# Searching all calls of the TurboWire constructor to check for unexpected input values
ast-grep --pattern $'new TurboWire($_, {maxRetries: $_, retryInterval: $_})'

Length of output: 77


Action Required: Validate External Inputs for TurboWire Constructor

The new private fields for retry logic are correctly introduced for reconnection behavior. However, as noted, it is important to ensure that invalid input (such as negative values for maxRetries or retryInterval) is properly handled. Our automated search using the provided ast-grep command did not yield any conclusive results for calls to the TurboWire constructor with these parameters. Therefore, please manually verify whether any external code passes invalid values to these properties. If such cases exist, consider adding an explicit check or a reasonable fallback in the constructor to mitigate potential edge cases.

  • File: packages/web/src/index.ts
  • Concern: Validate inputs for maxRetries and retryInterval passed to TurboWire.
packages/web/package.json (3)

13-13: Consolidating the "files" array into a single entry.

This is a minor formatting change. Having the array in one line is acceptable and doesn’t introduce any functional issues.


16-17: Added "prepublishOnly" script.

Running "npm run build" automatically before publishing is a best practice to ensure consumers receive the latest compiled code. Good addition!


19-22:

✅ Verification successful

Removed @types/node from devDependencies.

Before removing, confirm that no Node-specific global definitions (e.g., process, Buffer, or __dirname) are in use. If they are, the code might break without the Node type definitions.

Here’s a script to scan the codebase for references to Node-specific globals or imports:


🏁 Script executed:

#!/bin/bash
# Searching references to fs, path, process, or other node built-in modules
rg -i "require('fs')|from 'fs'|require('path')|from 'path'|process\\.|Buffer\\.|__dirname|__filename"

Length of output: 715


Subject: Verified Safe Removal of @types/node for packages/web

  • The grep search confirms that no Node-specific globals (e.g., process, Buffer, __dirname) are referenced in the packages/web directory.
  • Node-specific globals were only found in packages/serverless (e.g., usage of process.env), which is separate from the web package.
  • Therefore, removing @types/node from packages/web/package.json is safe as it does not impact the web codebase.

@arjunkomath arjunkomath merged commit 033a07f into main Mar 9, 2025
1 check passed
@arjunkomath arjunkomath deleted the feat/web-connection-retry branch March 9, 2025 05:13
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant