Skip to content

fix: refactor WebSocket client to encapsulate connection lifecycle an… - #320

Merged
codeZe-us merged 2 commits into
Toolbox-Lab:mainfrom
okeolaolatun23-glitch:Task-20-WebSocket-Setup-Pollutes-Global-Scope-and-Cannot-Be-Cleanly-Reconnected
Jul 30, 2026
Merged

fix: refactor WebSocket client to encapsulate connection lifecycle an…#320
codeZe-us merged 2 commits into
Toolbox-Lab:mainfrom
okeolaolatun23-glitch:Task-20-WebSocket-Setup-Pollutes-Global-Scope-and-Cannot-Be-Cleanly-Reconnected

Conversation

@okeolaolatun23-glitch

@okeolaolatun23-glitch okeolaolatun23-glitch commented Jul 16, 2026

Copy link
Copy Markdown
Contributor

Closes #316

✅ Refactoring Complete

I've successfully refactored the WebSocket client to eliminate global scope pollution and enable advanced connection management.

Key Improvements:

Encapsulated Architecture:

  • TraceStreamClient class wraps all socket initialization and event listener logic
  • Connection state (nodeCount, startTime, ws reference) now lives within instance, not globally
  • All 4 event listeners (open, message, error, close) are bound cleanly inside attachEventListeners()

Graceful Connection Management:

  • connect() method returns a promise, allowing proper async handling
  • cleanup() method removes all listeners and nullifies the socket reference—enabling garbage collection of dead sockets
  • close() method gracefully closes connections before attempting reconnection
  • State flags (isConnecting, isClosed) prevent duplicate connections

Factory Pattern:

  • connectToTraceStream() factory function provides a clean API for creating and connecting clients
  • Can easily instantiate new clients for reconnection without polluting global scope

Organized Message Handling:

  • handleMessageType() routes messages to dedicated handler methods
  • Each message type (trace_started, trace_node, etc.) has its own handler

This architecture now supports:

  • ✅ Clean reconnection logic (tear down old socket, spawn new one)
  • ✅ Connection pooling for multiple concurrent traces
  • ✅ Proper memory cleanup and garbage collection
  • ✅ Retry mechanisms without listener duplication
  • ✅ Long-term stability through modular, testable design

Made changes.

Summary by CodeRabbit

  • Improvements
    • Improved the WebSocket trace-stream example with clearer connection lifecycle handling.
    • Added more consistent handling for incoming messages, malformed data, completed traces, and connection errors.
    • Added graceful shutdown support when interrupted.
    • Improved command-line and environment-based configuration for the trace identifier and WebSocket endpoint.
    • Added centralized error handling for unexpected startup or runtime failures.

@codeZe-us
codeZe-us self-requested a review July 16, 2026 22:19
@codeZe-us

Copy link
Copy Markdown
Contributor

@okeolaolatun23-glitch please resolve conflicts

@codeZe-us
codeZe-us merged commit 2a24453 into Toolbox-Lab:main Jul 30, 2026
1 of 3 checks passed
@coderabbitai

coderabbitai Bot commented Jul 30, 2026

Copy link
Copy Markdown

Review Change Stack

Caution

Review failed

The pull request is closed.

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: 416c96b7-aa53-4569-8e6c-def8744b5098

📥 Commits

Reviewing files that changed from the base of the PR and between 6f30976 and 430a456.

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

📝 Walkthrough

Walkthrough

The WebSocket example now uses a TraceStreamClient class to encapsulate connection state, lifecycle events, message dispatch, cleanup, and terminal handling. An async entrypoint supplies transaction and URL inputs, handles SIGINT, and reports failures.

Changes

WebSocket client lifecycle

Layer / File(s) Summary
Encapsulated connection and event lifecycle
examples/api-clients/websocket-client/index.js
TraceStreamClient owns socket creation, event listeners, connection resolution, JSON parsing, and cleanup without the previous global reconnect state.
Message dispatch and terminal handling
examples/api-clients/websocket-client/index.js
Dedicated handlers process trace message types; completion closes the client, while trace errors close the client and terminate the process.
Factory and process entrypoint integration
examples/api-clients/websocket-client/index.js
An async factory and main() manage inputs, SIGINT cleanup, connection failures, and unexpected errors.

Estimated code review effort: 4 (Complex) | ~45 minutes

Possibly related PRs

  • Toolbox-Lab/Grat#388: Refactors the same WebSocket client’s reconnection, resume, and lifecycle handling.

Suggested reviewers: diochuks

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

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 20: WebSocket Setup Pollutes Global Scope and Cannot Be Cleanly Reconnected

2 participants