websocket.go


Overview

The [websocket.go](/projects/291/69273) file provides the implementation of a WebSocket connection handler tailored for the **Unchained API server**. It manages individual WebSocket client connections, processes incoming messages (such as subscription requests), maintains connection health through heartbeat mechanisms (ping/pong), and facilitates asynchronous message delivery from server-side event handlers to connected clients.

Key features include:

This file is critical for enabling real-time, event-driven communication between clients and the Unchained API via WebSockets.


Detailed Explanation

Types and Constants

Constants

Constant

Description

`writeWait`

Maximum duration for writing a message (15 seconds)

`readWait`

Maximum duration to wait for a new message (15 seconds)

`pingPeriod`

Frequency of sending ping messages (90% of `readWait`)

`maxMessageSize`

Maximum size of inbound message payload (1024 bytes)

Structs


RequestPayload

Represents the structure of a JSON message received from the client.

type RequestPayload struct {
    Data struct {
        Topic     string   `json:"topic"`
        Addresses []string `json:"addresses"`
    } `json:"data"`
    Method         string `json:"method"`
    SubscriptionID string `json:"subscriptionId"`
}

ErrorResponse

Represents the JSON structure for sending error messages to clients.

type ErrorResponse struct {
    Message        string `json:"message"`
    SubscriptionID string `json:"subscriptionId"`
    Type           string `json:"type"` // Always set to "error"
}

MessageResponse

Represents the JSON structure for sending data messages to clients.

type MessageResponse struct {
    Address        string      `json:"address"`
    Data           interface{} `json:"data"`
    SubscriptionID string      `json:"subscriptionId"`
}

Connection

Represents a single WebSocket client connection.

type Connection struct {
    clientID        string
    conn            *websocket.Conn
    doneChan        chan interface{}
    handler         Registrar
    manager         *Manager
    msgChan         chan []byte
    subscriptionIDs map[string]struct{}
    ticker          *time.Ticker
    m               sync.Mutex
}

Functions and Methods

NewConnection

func NewConnection(conn *websocket.Conn, handler Registrar, manager *Manager) *Connection
newConn := NewConnection(wsConn, subscriptionHandler, connectionManager)

(*Connection) Start

func (c *Connection) Start()

(*Connection) Stop

func (c *Connection) Stop()

(*Connection) cleanup

func (c *Connection) cleanup()

(*Connection) send

func (c *Connection) send(messageType int, data []byte) error

(*Connection) read

func (c *Connection) read()

(*Connection) write

func (c *Connection) write()

(*Connection) writeError

func (c *Connection) writeError(message string, subscriptionID string)

Important Implementation Details and Algorithms


Interaction with Other System Components

This file is a core part of the WebSocket communication layer, enabling client subscription management, message handling, and connection lifecycle management within the Unchained API server.


Visual Diagram

classDiagram
    class Connection {
        -clientID: string
        -conn: *websocket.Conn
        -doneChan: chan interface{}
        -handler: Registrar
        -manager: *Manager
        -msgChan: chan []byte
        -subscriptionIDs: map[string]struct{}
        -ticker: *time.Ticker
        -m: sync.Mutex
        +Start()
        +Stop()
        +read()
        +write()
        +send(messageType int, data []byte) error
        +writeError(message string, subscriptionID string)
        +cleanup()
    }

    class RequestPayload {
        +Data: struct { Topic string; Addresses []string }
        +Method: string
        +SubscriptionID: string
    }

    class ErrorResponse {
        +Message: string
        +SubscriptionID: string
        +Type: string
    }

    class MessageResponse {
        +Address: string
        +Data: interface{}
        +SubscriptionID: string
    }

    Connection --> Registrar : handler (interface)
    Connection --> Manager : manager (manages connections)

Usage Example

// Assume wsConn is an established *websocket.Conn,
// subscriptionHandler implements Registrar,
// and connectionManager manages all connections.

conn := websocket.NewConnection(wsConn, subscriptionHandler, connectionManager)
conn.Start()

// When done or on error
conn.Stop()

Summary

The [websocket.go](/projects/291/69273) file encapsulates the management of WebSocket connections to the Unchained API server. It provides a robust, concurrent, and maintainable structure to handle real-time client subscriptions, message exchange, and connection health monitoring, relying on external subscription and connection management components for broader system integration.