Skip to content

Conversation

Copy link
Contributor

Copilot AI commented Oct 10, 2025

Overview

This PR implements the ability to route API requests through WebSocket connections instead of HTTP when the WebSocket feature flag is enabled and a connection is active. This provides a more efficient real-time communication channel while maintaining full backward compatibility.

Problem Statement

The application previously used only HTTP REST API calls for all operations. With WebSocket infrastructure already in place, we needed a way to route API requests through WebSocket connections when available to improve performance and reduce overhead.

Solution

Added intelligent request routing that checks if WebSocket is enabled and connected, then automatically routes supported API operations through WebSocket while falling back to HTTP for unsupported operations or when WebSocket is unavailable.

Implementation Details

1. Extended WebSocket Type Definitions

Added comprehensive WebSocket action types and payload definitions for all API operations:

export type WSAction =
  | 'get_user_labels' | 'create_label' | 'update_label' | 'delete_label'
  | 'get_tasks' | 'create_task' | 'update_task' | 'delete_task'
  | 'complete_task' | 'skip_task' | 'update_due_date'
  | 'get_app_tokens' | 'create_app_token' | 'delete_app_token'
  | 'get_user_profile' | 'update_password' | 'update_notification_settings'
  // ... and more

2. Enhanced WebSocketManager

Added sendRequest() method that implements request/response correlation:

async sendRequest<T extends WSAction>(
  action: T,
  data?: WSActionPayloads[T],
  timeout: number = 5000
): Promise<{ status: number; data: any }>

Features:

  • Secure UUID-based request IDs using crypto.randomUUID() with fallback
  • Response structure validation to prevent errors
  • 5-second timeout with proper cleanup
  • Direct message event handling for matched responses

3. Modified Request Function

The main Request() function now:

// Check if WebSocket should be used
const state = store.getState()
const useWebSocket = state.featureFlags.useWebsockets && requiresAuth

if (useWebSocket) {
  const wsManager = WebSocketManager.getInstance()
  if (wsManager.isConnected()) {
    const wsMapping = mapRequestToWebSocket(url, method)
    if (wsMapping) {
      try {
        // Send via WebSocket
        const response = await wsManager.sendRequest(wsMapping.action, wsData)
        return response.data
      } catch (error) {
        // Fall back to HTTP on any error
        console.debug('WebSocket request failed, falling back to HTTP:', error)
      }
    }
  }
}

// Fall back to HTTP request
const response = await fetch(fullURL, options)

4. URL to WebSocket Action Mapping

Comprehensive mapping function translates HTTP endpoints to WebSocket actions:

// Example mappings:
GET /labels  get_user_labels
POST /tasks/  create_task
POST /tasks/:id/do  complete_task
DELETE /labels/:id  delete_label { id }

Supported Operations

All major API operations now support WebSocket routing:

  • Labels: Get all, create, update, delete
  • Tasks: Get active/completed, create, update, delete, complete, skip, update due date, get history
  • API Tokens: Get all, create, delete
  • User Profile: Get profile, update password, update notification settings

Behavior

When WebSocket is enabled and connected:

  • Supported operations route through WebSocket
  • Unsupported operations fall back to HTTP
  • Errors automatically fall back to HTTP

When WebSocket is disabled or disconnected:

  • All operations use HTTP (existing behavior)
  • Zero impact on functionality

Key Features

✅ Feature flag controlled (useWebsockets)
✅ Connection status validation
✅ Automatic HTTP fallback on errors
✅ Request/response correlation via UUID
✅ Response structure validation
✅ Type-safe error handling
✅ Zero breaking changes
✅ Full backward compatibility

Testing

  • All existing tests pass (78/78)
  • Code passes linting with no errors
  • TypeScript compilation successful
  • Production build successful
  • Maintains 100% backward compatibility

Code Quality Improvements

  • Extracted HTTP_STATUS_NO_CONTENT constant to module level
  • Replaced any types with proper FailureResponse interface
  • Enhanced request ID generation with crypto API
  • Added comprehensive response validation

Example Usage

No code changes required! Simply enable the WebSocket feature flag:

store.dispatch(setFlag({ name: 'useWebsockets', value: true }))

All API calls will automatically route through WebSocket when connected, with transparent fallback to HTTP when needed.

Original prompt

Instead of using HTTP for requests to the api server, check if websocket feature flag is enabled And connected send websocket requests instead of the rest http ones.


💡 You can make Copilot smarter by setting up custom instructions, customizing its development environment and configuring Model Context Protocol (MCP) servers. Learn more Copilot coding agent tips in the docs.

Copilot AI changed the title [WIP] Add support for websocket requests based on feature flag Add WebSocket request support as alternative to HTTP API calls Oct 10, 2025
Copilot AI requested a review from dkhalife October 10, 2025 20:37
dkhalife added a commit that referenced this pull request Oct 11, 2025
Co-authored-by: copilot-swe-agent[bot] <[email protected]>
Co-authored-by: dkhalife <[email protected]>
@codecov
Copy link

codecov bot commented Oct 18, 2025

Codecov Report

✅ All modified and coverable lines are covered by tests.

📢 Thoughts on this report? Let us know!

@dkhalife dkhalife closed this Dec 14, 2025
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.

2 participants