Skip to content

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

Open
okeolaolatun23-glitch wants to merge 1 commit into
Toolbox-Lab:mainfrom
okeolaolatun23-glitch:Task-20-WebSocket-Setup-Pollutes-Global-Scope-and-Cannot-Be-Cleanly-Reconnected
Open

fix: refactor WebSocket client to encapsulate connection lifecycle an…#320
okeolaolatun23-glitch wants to merge 1 commit into
Toolbox-Lab:mainfrom
okeolaolatun23-glitch:Task-20-WebSocket-Setup-Pollutes-Global-Scope-and-Cannot-Be-Cleanly-Reconnected

Conversation

@okeolaolatun23-glitch

Copy link
Copy Markdown

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.

@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

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