adapter

package module
v3.0.6 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jun 20, 2026 License: MIT Imports: 15 Imported by: 0

README

socket.io-go-adapter

Go Reference Go Report Card

Description

A base adapter implementation for Socket.IO server in Go, providing core functionality for building custom adapters and scaling Socket.IO applications.

Installation

go get github.com/technance-foundation/socket.io/adapters/adapter/v3

Features

  • Base adapter interface and implementation
  • Cluster adapter support
  • Session-aware adapter capabilities
  • Heartbeat mechanism for cluster communication
  • Remote socket handling
  • Extensible adapter architecture

How to use

Basic usage example:

package main

import (
    "github.com/technance-foundation/socket.io/adapters/adapter/v3"
    "github.com/technance-foundation/socket.io/servers/socket/v3"
)

func main() {
    // Create Socket.IO server configuration
    config := socket.DefaultServerOptions()

    // Use default adapter
    config.SetAdapter(&adapter.AdapterBuilder{})

    // Create server with adapter
    io := socket.NewServer(nil, config)

    // Handle connections
    io.On("connection", func(clients ...any) {
        client := clients[0].(*socket.Socket)
        // Your connection handling logic
    })
}

Adapter Types

The package provides several adapter implementations:

  1. Base Adapter
type Adapter interface {
    Broadcast([]Room, *BroadcastOptions, ...any)
    BroadcastWithAck([]Room, *BroadcastOptions, ...any) <-chan []any
    // ... other methods
}
  1. Cluster Adapter
type ClusterAdapter interface {
    Adapter
    ServerCount() int
    // Additional cluster-specific methods
}
  1. Session-Aware Adapter
type SessionAwareAdapter interface {
    Adapter
    SaveSession(id string, session any)
    GetSession(id string) any
    // Session management methods
}

Configuration Options

ClusterAdapterOptions
type ClusterAdapterOptions struct {
    HeartbeatInterval time.Duration
    HeartbeatTimeout  time.Duration
}

Testing

Run the test suite with:

make test

Contributing

  1. Fork the repository
  2. Create your feature branch (git checkout -b feature/amazing-feature)
  3. Commit your changes (git commit -m 'Add some amazing feature')
  4. Push to the branch (git push origin feature/amazing-feature)
  5. Open a Pull Request

Support

If you encounter any issues or have questions, please file them in the issues section.

License

This project is licensed under the MIT License - see the LICENSE file for details.

Documentation

Index

Constants

View Source
const VERSION = version.VERSION

Variables

This section is empty.

Functions

func DecodeOptions

func DecodeOptions(opts *PacketOptions) *socket.BroadcastOptions

DecodeOptions decodes PacketOptions back into BroadcastOptions.

func RandomId

func RandomId() string

RandomId generates a random hexadecimal string of 8 bytes.

func Uid2

func Uid2(length int) string

Uid2 generates a random URL-safe base64 string of the given length.

Types

type Adapter

type Adapter = socket.Adapter

Adapter is an alias for socket.Adapter.

func MakeAdapter

func MakeAdapter() Adapter

MakeAdapter returns a new default Adapter instance.

func NewAdapter

func NewAdapter(nsp socket.Namespace) Adapter

NewAdapter creates a new Adapter for the given Namespace.

type AdapterBuilder

type AdapterBuilder struct {
}

AdapterBuilder is a builder for creating Adapter instances.

func (*AdapterBuilder) New

New creates a new Adapter for the given Namespace.

type BroadcastAck

type BroadcastAck struct {
	RequestId string `json:"requestId,omitempty" msgpack:"requestId,omitempty"`
	Packet    []any  `json:"packet,omitempty" msgpack:"packet,omitempty"`
}

BroadcastAck represents a broadcast acknowledgment.

type BroadcastClientCount

type BroadcastClientCount struct {
	RequestId   string `json:"requestId,omitempty" msgpack:"requestId,omitempty"`
	ClientCount uint64 `json:"clientCount,omitempty" msgpack:"clientCount,omitempty"`
}

BroadcastClientCount represents a broadcast client count.

type BroadcastMessage

type BroadcastMessage struct {
	Opts      *PacketOptions `json:"opts,omitempty" msgpack:"opts,omitempty"`
	Packet    *parser.Packet `json:"packet,omitempty" msgpack:"packet,omitempty"`
	RequestId *string        `json:"requestId,omitempty" msgpack:"requestId,omitempty"`
}

BroadcastMessage is a message for broadcasting.

type ClusterAckRequest

type ClusterAckRequest struct {
	ClientCountCallback func(uint64)
	Ack                 socket.Ack
}

ClusterAckRequest represents a cluster acknowledgment request.

type ClusterAdapter

type ClusterAdapter interface {
	Adapter

	// Uid returns the unique server ID.
	Uid() ServerId
	// OnMessage handles an incoming cluster message with its offset.
	OnMessage(*ClusterMessage, Offset)
	// OnResponse handles an incoming cluster response.
	OnResponse(*ClusterResponse)
	// Publish sends a cluster message to other nodes.
	Publish(*ClusterMessage)
	// PublishAndReturnOffset sends a message and returns its offset.
	PublishAndReturnOffset(*ClusterMessage) (Offset, error)
	// DoPublish performs the actual publish operation and returns the offset.
	DoPublish(*ClusterMessage) (Offset, error)
	// PublishResponse sends a response to a specific server.
	PublishResponse(ServerId, *ClusterResponse)
	// DoPublishResponse performs the actual publish response operation.
	DoPublishResponse(ServerId, *ClusterResponse) error
}

ClusterAdapter is an interface for a cluster-ready adapter. Any implementation must provide methods for publishing messages and responses across the cluster.

func MakeClusterAdapter

func MakeClusterAdapter() ClusterAdapter

MakeClusterAdapter returns a new default ClusterAdapter instance.

func NewClusterAdapter

func NewClusterAdapter(nsp socket.Namespace) ClusterAdapter

NewClusterAdapter creates a new ClusterAdapter for the given Namespace.

type ClusterAdapterBuilder

type ClusterAdapterBuilder struct{}

ClusterAdapterBuilder is a builder for creating ClusterAdapter instances.

A cluster-ready adapter. Any extending interface must:

  • implement ClusterAdapter.DoPublish and ClusterAdapter.DoPublishResponse
  • call ClusterAdapter.OnMessage and ClusterAdapter.OnResponse

func (*ClusterAdapterBuilder) New

New creates a new ClusterAdapter for the given Namespace.

type ClusterAdapterOptions

type ClusterAdapterOptions struct {
	// contains filtered or unexported fields
}

ClusterAdapterOptions holds configuration for cluster adapter heartbeat and timeout.

func DefaultClusterAdapterOptions

func DefaultClusterAdapterOptions() *ClusterAdapterOptions

func (*ClusterAdapterOptions) GetRawHeartbeatInterval

func (s *ClusterAdapterOptions) GetRawHeartbeatInterval() types.Optional[time.Duration]

func (*ClusterAdapterOptions) GetRawHeartbeatTimeout

func (s *ClusterAdapterOptions) GetRawHeartbeatTimeout() types.Optional[int64]

func (*ClusterAdapterOptions) HeartbeatInterval

func (s *ClusterAdapterOptions) HeartbeatInterval() time.Duration

func (*ClusterAdapterOptions) HeartbeatTimeout

func (s *ClusterAdapterOptions) HeartbeatTimeout() int64

func (*ClusterAdapterOptions) SetHeartbeatInterval

func (s *ClusterAdapterOptions) SetHeartbeatInterval(heartbeatInterval time.Duration)

func (*ClusterAdapterOptions) SetHeartbeatTimeout

func (s *ClusterAdapterOptions) SetHeartbeatTimeout(heartbeatTimeout int64)

type ClusterAdapterOptionsInterface

type ClusterAdapterOptionsInterface interface {
	SetHeartbeatInterval(time.Duration)
	GetRawHeartbeatInterval() types.Optional[time.Duration]
	HeartbeatInterval() time.Duration

	SetHeartbeatTimeout(int64)
	GetRawHeartbeatTimeout() types.Optional[int64]
	HeartbeatTimeout() int64
}

ClusterAdapterOptionsInterface defines the interface for cluster adapter options.

type ClusterAdapterWithHeartbeat

type ClusterAdapterWithHeartbeat interface {
	ClusterAdapter

	SetOpts(any)
}

ClusterAdapterWithHeartbeat extends ClusterAdapter with heartbeat and custom options support.

func MakeClusterAdapterWithHeartbeat

func MakeClusterAdapterWithHeartbeat() ClusterAdapterWithHeartbeat

func NewClusterAdapterWithHeartbeat

func NewClusterAdapterWithHeartbeat(nsp socket.Namespace, opts any) ClusterAdapterWithHeartbeat

type ClusterAdapterWithHeartbeatBuilder

type ClusterAdapterWithHeartbeatBuilder struct {
	Opts ClusterAdapterOptionsInterface
}

ClusterAdapterWithHeartbeatBuilder is a builder for creating ClusterAdapterWithHeartbeat instances.

func (*ClusterAdapterWithHeartbeatBuilder) New

type ClusterMessage

type ClusterMessage struct {
	Uid  ServerId    `json:"uid,omitempty" msgpack:"uid,omitempty"`
	Nsp  string      `json:"nsp,omitempty" msgpack:"nsp,omitempty"`
	Type MessageType `json:"type,omitempty" msgpack:"type,omitempty"`
	Data any         `json:"data,omitempty" msgpack:"data,omitempty"` // Data will hold the specific message data for different types
}

ClusterMessage contains common fields for all cluster messages.

type ClusterRequest

type ClusterRequest struct {
	Type      MessageType
	Resolve   func(*types.Slice[any])
	Timeout   *atomic.Pointer[utils.Timer]
	Expected  int64
	Current   *atomic.Int64
	Responses *types.Slice[any]
	Once      sync.Once // guards against double callback invocation (timeout vs response race)
}

ClusterRequest represents a cluster request.

type ClusterResponse

type ClusterResponse = ClusterMessage

type CustomClusterRequest

type CustomClusterRequest struct {
	Type        MessageType
	Resolve     func(*types.Slice[any])
	Timeout     *atomic.Pointer[utils.Timer]
	MissingUids *types.Set[ServerId]
	Responses   *types.Slice[any]
	Once        sync.Once // guards against double callback invocation (timeout vs response race)
}

CustomClusterRequest represents a custom request in the cluster with tracking for missing responses.

type DisconnectSocketsMessage

type DisconnectSocketsMessage struct {
	Opts  *PacketOptions `json:"opts,omitempty" msgpack:"opts,omitempty"`
	Close bool           `json:"close,omitempty" msgpack:"close,omitempty"`
}

DisconnectSocketsMessage is a message for disconnecting sockets.

type FetchSocketsMessage

type FetchSocketsMessage struct {
	Opts      *PacketOptions `json:"opts,omitempty" msgpack:"opts,omitempty"`
	RequestId string         `json:"requestId,omitempty" msgpack:"requestId,omitempty"`
}

FetchSocketsMessage is a message for fetching sockets.

type FetchSocketsResponse

type FetchSocketsResponse struct {
	RequestId string            `json:"requestId,omitempty" msgpack:"requestId,omitempty"`
	Sockets   []*SocketResponse `json:"sockets,omitempty" msgpack:"sockets,omitempty"`
}

FetchSocketsResponse represents a response for fetching sockets.

type MessageType

type MessageType int

MessageType represents the type of cluster message.

const (
	INITIAL_HEARTBEAT MessageType = iota + 1
	HEARTBEAT
	BROADCAST
	SOCKETS_JOIN
	SOCKETS_LEAVE
	DISCONNECT_SOCKETS
	FETCH_SOCKETS
	FETCH_SOCKETS_RESPONSE
	SERVER_SIDE_EMIT
	SERVER_SIDE_EMIT_RESPONSE
	BROADCAST_CLIENT_COUNT
	BROADCAST_ACK
	ADAPTER_CLOSE
)

func (MessageType) IsValid

func (m MessageType) IsValid() bool

IsValid performs a fast bounds check to ensure the MessageType is within defined enum constants.

type Offset

type Offset string

Offset is the unique ID of a message (for the connection state recovery feature).

type PacketOptions

type PacketOptions struct {
	Rooms  []socket.Room          `json:"rooms,omitempty" msgpack:"rooms,omitempty"`
	Except []socket.Room          `json:"except,omitempty" msgpack:"except,omitempty"`
	Flags  *socket.BroadcastFlags `json:"flags,omitempty" msgpack:"flags,omitempty"`
}

PacketOptions represents the options for broadcasting messages.

func EncodeOptions

func EncodeOptions(opts *socket.BroadcastOptions) *PacketOptions

EncodeOptions encodes BroadcastOptions into PacketOptions.

type RemoteSocket

type RemoteSocket struct {
	// contains filtered or unexported fields
}

RemoteSocket exposes a subset of the attributes and methods of the Socket struct.

func MakeRemoteSocket

func MakeRemoteSocket() *RemoteSocket

MakeRemoteSocket creates a new empty RemoteSocket instance.

func NewRemoteSocket

func NewRemoteSocket(details *SocketResponse) *RemoteSocket

NewRemoteSocket creates a new RemoteSocket from the given SocketResponse details.

func (*RemoteSocket) Construct

func (r *RemoteSocket) Construct(details *SocketResponse)

Construct initializes the RemoteSocket from the given SocketResponse details.

func (*RemoteSocket) Data

func (r *RemoteSocket) Data() any

Data returns the custom data associated with the remote socket.

func (*RemoteSocket) Handshake

func (r *RemoteSocket) Handshake() *socket.Handshake

Handshake returns the handshake information of the remote socket.

func (*RemoteSocket) Id

func (r *RemoteSocket) Id() socket.SocketId

Id returns the socket ID of the remote socket.

func (*RemoteSocket) Rooms

func (r *RemoteSocket) Rooms() *types.Set[socket.Room]

Rooms returns the set of rooms the remote socket has joined.

type ServerId

type ServerId string

ServerId is the unique ID of a server.

const (
	EMITTER_UID     ServerId      = "emitter"
	DEFAULT_TIMEOUT time.Duration = 5_000 * time.Millisecond
)

type ServerSideEmitMessage

type ServerSideEmitMessage struct {
	RequestId *string `json:"requestId,omitempty" msgpack:"requestId,omitempty"`
	Packet    []any   `json:"packet,omitempty" msgpack:"packet,omitempty"`
}

ServerSideEmitMessage is a message for server-side emit.

type ServerSideEmitResponse

type ServerSideEmitResponse struct {
	RequestId string `json:"requestId,omitempty" msgpack:"requestId,omitempty"`
	Packet    []any  `json:"packet,omitempty" msgpack:"packet,omitempty"`
}

ServerSideEmitResponse represents a response for server-side emit.

type SessionAwareAdapter

type SessionAwareAdapter = socket.SessionAwareAdapter

SessionAwareAdapter is an alias for socket.SessionAwareAdapter.

func MakeSessionAwareAdapter

func MakeSessionAwareAdapter() SessionAwareAdapter

MakeSessionAwareAdapter returns a new default SessionAwareAdapter instance.

func NewSessionAwareAdapter

func NewSessionAwareAdapter(nsp socket.Namespace) SessionAwareAdapter

NewSessionAwareAdapter creates a new SessionAwareAdapter for the given Namespace.

type SessionAwareAdapterBuilder

type SessionAwareAdapterBuilder struct {
}

SessionAwareAdapterBuilder is a builder for creating SessionAwareAdapter instances.

func (*SessionAwareAdapterBuilder) New

New creates a new SessionAwareAdapter for the given Namespace.

type SocketResponse

type SocketResponse struct {
	Id        socket.SocketId   `json:"id,omitempty" msgpack:"id,omitempty"`
	Handshake *socket.Handshake `json:"handshake,omitempty" msgpack:"handshake,omitempty"`
	Rooms     []socket.Room     `json:"rooms,omitempty" msgpack:"rooms,omitempty"`
	Data      any               `json:"data,omitempty" msgpack:"data,omitempty"`
}

SocketResponse represents a socket response.

type SocketsJoinLeaveMessage

type SocketsJoinLeaveMessage struct {
	Opts  *PacketOptions `json:"opts,omitempty" msgpack:"opts,omitempty"`
	Rooms []socket.Room  `json:"rooms,omitempty" msgpack:"rooms,omitempty"`
}

SocketsJoinLeaveMessage is a message for joining or leaving sockets.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL