Skip to content

chore: added websocket pkg & client reconnection state - #388

Merged
codeZe-us merged 3 commits into
Toolbox-Lab:mainfrom
DioChuks:fix/websocket-client
Jul 30, 2026
Merged

chore: added websocket pkg & client reconnection state#388
codeZe-us merged 3 commits into
Toolbox-Lab:mainfrom
DioChuks:fix/websocket-client

Conversation

@DioChuks

@DioChuks DioChuks commented Jul 29, 2026

Copy link
Copy Markdown
Contributor

Summary

Refactored index.js to convert the WebSocket trace client into an autonomous self-healing system capable of surviving transient network blips and server restarts.

Changes Made

WebSocket Client Example

index.js

  • Renamed connection entry point: Created connectToTraceStream() as the primary connection method.
  • Implemented autonomous reconnection engine:
    • Added reconnect() method with persistent attempt counting (reconnectAttempts).
    • Added exponential backoff delay calculation using Math.min(MAX_RECONNECT_DELAY, INITIAL_RECONNECT_DELAY * Math.pow(2, reconnectAttempts - 1)).
    • Added setTimeout call to asynchronously trigger connectToTraceStream().
    • Enforced MAX_RECONNECT_ATTEMPTS = 10 threshold before exiting.
  • Rewrote socket event handlers:
    • ws.on('error'): Logs the error and invokes reconnect().
    • ws.on('close'): Checks if client was intentionally stopped (stopped), otherwise invokes reconnect().
  • Preserved state synchronization:
    • Maintained lastSeenNodeId outside connection scope for resume_from resume cursor upon reconnection.
    • Reset reconnectAttempts = 0 on successful open event.

Verification Results

Automated & Manual Testing

  1. Syntax check via node --check passed cleanly with no errors.
  2. Simulated connection failures against an offline endpoint logged:
    Connecting to ws://localhost:9999...
    WebSocket error: AggregateError
    Connection lost. Reconnecting in 1s...
    WebSocket error: AggregateError
    Connection lost. Reconnecting in 2s...
    WebSocket error: AggregateError
    Connection lost. Reconnecting in 4s...
    WebSocket error: AggregateError
    Connection lost. Reconnecting in 5s...
    

Closes #317

Summary by CodeRabbit

  • Bug Fixes
    • Improved WebSocket reconnection behavior after errors or unexpected closures.
    • Prevented multiple reconnection attempts from running at the same time and stopped after a capped number of failures.
    • Hardened WebSocket event and lifecycle handling to ignore stale events and properly close the active socket on completion/error.
    • Added an explicit WebSocket handshake timeout to improve startup reliability.
  • Chores
    • Updated the WebSocket client library dependency.

@coderabbitai

coderabbitai Bot commented Jul 29, 2026

Copy link
Copy Markdown

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: 7b7c9e55-883f-47c9-9e08-016a08d2943d

📥 Commits

Reviewing files that changed from the base of the PR and between 5c41799 and f52284c.

📒 Files selected for processing (1)
  • examples/api-clients/websocket-client/index.js
🚧 Files skipped from review as they are similar to previous changes (1)
  • examples/api-clients/websocket-client/index.js

📝 Walkthrough

Walkthrough

The WebSocket client now uses per-connection lifecycle guards and a centralized reconnect() flow with exponential delays, capped attempts, handshake timeouts, and reset state after successful connections. The ws dependency is updated to ^8.19.0.

Changes

WebSocket reconnection lifecycle

Layer / File(s) Summary
Connection setup and lifecycle
examples/api-clients/websocket-client/index.js, examples/api-clients/websocket-client/package.json
Connections use captured socket references, stale-event guards, an explicit handshake timeout, trace termination cleanup, and the connectToTraceStream() startup entry point; ws is updated to ^8.19.0.
Guarded reconnect control
examples/api-clients/websocket-client/index.js
Error and close events invoke reconnect(), which prevents overlapping attempts, applies exponential backoff, exits after the retry limit, and schedules a new trace-stream connection.

Estimated code review effort: 3 (Moderate) | ~20 minutes

Sequence Diagram(s)

sequenceDiagram
  participant WebSocket
  participant reconnect
  participant connectToTraceStream
  WebSocket->>reconnect: error or close event
  reconnect->>reconnect: validate reconnect state
  reconnect->>reconnect: calculate exponential delay
  reconnect->>connectToTraceStream: invoke after timeout
  connectToTraceStream->>WebSocket: establish timed trace-stream connection
Loading

Possibly related issues

  • Issue 316: Requests the connectToTraceStream() encapsulation and per-connection WebSocket lifecycle management implemented in this change.
🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title matches the main change: websocket client reconnection behavior, with a secondary package bump also reflected.
Linked Issues check ✅ Passed The PR implements autonomous reconnect logic with retry tracking, backoff, setTimeout retries, and stream-state resumption.
Out of Scope Changes check ✅ Passed The dependency bump and handshake timeout are directly related to the websocket reconnect changes, so no clear out-of-scope edits appear.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
✨ Finishing Touches 💡 1
🛠️ Fix failing CI checks 💡
  • Fix failing CI checks
🧪 Generate unit tests (beta)
  • Create PR with unit tests

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🤖 Prompt for all review comments with 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.

Inline comments:
In `@examples/api-clients/websocket-client/index.js`:
- Around line 161-163: Update the reconnect timeout callback around
connectToTraceStream so it does not clear isReconnecting before creating the
replacement socket. Ensure delayed close events from superseded sockets are
ignored and cannot schedule additional retries, while preserving the single
reconnect flow.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: 4d90e1d3-e99e-4e87-9cec-af9a79a02cfb

📥 Commits

Reviewing files that changed from the base of the PR and between 130c7de and c1b3b81.

⛔ Files ignored due to path filters (1)
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
📒 Files selected for processing (2)
  • examples/api-clients/websocket-client/index.js
  • examples/api-clients/websocket-client/package.json

Comment thread examples/api-clients/websocket-client/index.js
@DioChuks

Copy link
Copy Markdown
Contributor Author

The CI Rust Checks isnt from my changes, pls review

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🤖 Prompt for all review comments with 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.

Inline comments:
In `@examples/api-clients/websocket-client/index.js`:
- Around line 44-45: Update the WebSocket construction in reconnect() to pass
the configured handshakeTimeout option to new WebSocket(WS_URL). Preserve the
existing socket assignment and error/close handlers so timed-out connection
attempts trigger the current retry flow.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: ade6508c-9c01-4c2b-9674-ce6dcf199233

📥 Commits

Reviewing files that changed from the base of the PR and between c1b3b81 and 5c41799.

📒 Files selected for processing (1)
  • examples/api-clients/websocket-client/index.js

Comment thread examples/api-clients/websocket-client/index.js Outdated
@codeZe-us
codeZe-us self-requested a review July 30, 2026 00:39
@codeZe-us
codeZe-us merged commit 4ebabf2 into Toolbox-Lab:main Jul 30, 2026
2 of 3 checks passed
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.

Task 21: WebSocket Client Exits Instead of Reconnecting After a Dropped Connection

2 participants