|
|
|
|
@@ -3,14 +3,13 @@ package client
|
|
|
|
|
import (
|
|
|
|
|
"context"
|
|
|
|
|
"fmt"
|
|
|
|
|
"io"
|
|
|
|
|
"log"
|
|
|
|
|
"net/url"
|
|
|
|
|
"strings"
|
|
|
|
|
"sync"
|
|
|
|
|
"time"
|
|
|
|
|
|
|
|
|
|
custom_rwmutex "git.neurocipta.com/rogerferdinan/custom-rwmutex"
|
|
|
|
|
safemap "git.neurocipta.com/rogerferdinan/safe-map"
|
|
|
|
|
"git.neurocipta.com/rogerferdinan/safe-web-socket/internal"
|
|
|
|
|
"github.com/gorilla/websocket"
|
|
|
|
|
)
|
|
|
|
|
@@ -20,59 +19,13 @@ const (
|
|
|
|
|
readDeadline = 30 * time.Second
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
type SafeMap[K comparable, V any] struct {
|
|
|
|
|
m sync.Map
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func NewSafeMap[K comparable, V any]() *SafeMap[K, V] {
|
|
|
|
|
return &SafeMap[K, V]{
|
|
|
|
|
m: sync.Map{},
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func (sm *SafeMap[K, V]) Store(key K, value V) {
|
|
|
|
|
sm.m.Store(key, value)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func (sm *SafeMap[K, V]) Load(key K) (value V, ok bool) {
|
|
|
|
|
val, loaded := sm.m.Load(key)
|
|
|
|
|
if !loaded {
|
|
|
|
|
return *new(V), false
|
|
|
|
|
}
|
|
|
|
|
return val.(V), true
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func (sm *SafeMap[K, V]) Delete(key K) {
|
|
|
|
|
sm.m.Delete(key)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func (sm *SafeMap[K, V]) Range(f func(K, V) bool) {
|
|
|
|
|
sm.m.Range(func(key, value any) bool {
|
|
|
|
|
k, ok1 := key.(K)
|
|
|
|
|
v, ok2 := value.(V)
|
|
|
|
|
if !ok1 || !ok2 {
|
|
|
|
|
return true
|
|
|
|
|
}
|
|
|
|
|
return f(k, v)
|
|
|
|
|
})
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func (sm *SafeMap[K, V]) Len() int {
|
|
|
|
|
count := 0
|
|
|
|
|
sm.Range(func(_ K, _ V) bool {
|
|
|
|
|
count++
|
|
|
|
|
return true
|
|
|
|
|
})
|
|
|
|
|
return count
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
type MessageType uint
|
|
|
|
|
|
|
|
|
|
const (
|
|
|
|
|
MessageTypeText MessageType = iota + 1
|
|
|
|
|
MessageTypePing MessageType = iota
|
|
|
|
|
MessageTypePong MessageType = iota
|
|
|
|
|
MessageTypeClose MessageType = iota
|
|
|
|
|
MessageTypeText MessageType = websocket.TextMessage
|
|
|
|
|
MessageTypePing MessageType = websocket.PingMessage
|
|
|
|
|
MessageTypePong MessageType = websocket.PongMessage
|
|
|
|
|
MessageTypeClose MessageType = websocket.CloseMessage
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
type Message struct {
|
|
|
|
|
@@ -81,13 +34,13 @@ type Message struct {
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
type SafeWebsocketClientBuilder struct {
|
|
|
|
|
baseHost *string `nil_checker:"required"`
|
|
|
|
|
basePort *uint16 `nil_checker:"required"`
|
|
|
|
|
path *string
|
|
|
|
|
rawQuery *string
|
|
|
|
|
useTLS *bool
|
|
|
|
|
channelSize *int64
|
|
|
|
|
authenticateFn func(*SafeWebsocketClient) error
|
|
|
|
|
baseHost *string `nil_checker:"required"`
|
|
|
|
|
basePort *uint16 `nil_checker:"required"`
|
|
|
|
|
path *string
|
|
|
|
|
rawQuery *string
|
|
|
|
|
isDrop *bool
|
|
|
|
|
useTLS *bool
|
|
|
|
|
channelSize *int64
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func NewSafeWebsocketClientBuilder() *SafeWebsocketClientBuilder {
|
|
|
|
|
@@ -109,11 +62,6 @@ func (b *SafeWebsocketClientBuilder) UseTLS(useTLS bool) *SafeWebsocketClientBui
|
|
|
|
|
return b
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func (b *SafeWebsocketClientBuilder) AuthenticateFn(authenticateFn func(*SafeWebsocketClient) error) *SafeWebsocketClientBuilder {
|
|
|
|
|
b.authenticateFn = authenticateFn
|
|
|
|
|
return b
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func (b *SafeWebsocketClientBuilder) Path(path string) *SafeWebsocketClientBuilder {
|
|
|
|
|
b.path = &path
|
|
|
|
|
return b
|
|
|
|
|
@@ -124,6 +72,11 @@ func (b *SafeWebsocketClientBuilder) RawQuery(rawQuery string) *SafeWebsocketCli
|
|
|
|
|
return b
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func (b *SafeWebsocketClientBuilder) IsDrop(isDrop bool) *SafeWebsocketClientBuilder {
|
|
|
|
|
b.isDrop = &isDrop
|
|
|
|
|
return b
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func (b *SafeWebsocketClientBuilder) ChannelSize(channelSize int64) *SafeWebsocketClientBuilder {
|
|
|
|
|
b.channelSize = &channelSize
|
|
|
|
|
return b
|
|
|
|
|
@@ -134,9 +87,15 @@ func (b *SafeWebsocketClientBuilder) Build(ctx context.Context) (*SafeWebsocketC
|
|
|
|
|
return nil, err
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
var useTLS bool
|
|
|
|
|
if b.useTLS != nil {
|
|
|
|
|
useTLS = *b.useTLS
|
|
|
|
|
// var useTLS bool
|
|
|
|
|
if b.useTLS == nil {
|
|
|
|
|
useTLS := true
|
|
|
|
|
b.useTLS = &useTLS
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if b.isDrop == nil {
|
|
|
|
|
isDrop := true
|
|
|
|
|
b.isDrop = &isDrop
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if b.channelSize == nil {
|
|
|
|
|
@@ -147,7 +106,8 @@ func (b *SafeWebsocketClientBuilder) Build(ctx context.Context) (*SafeWebsocketC
|
|
|
|
|
wsClient := SafeWebsocketClient{
|
|
|
|
|
baseHost: *b.baseHost,
|
|
|
|
|
basePort: *b.basePort,
|
|
|
|
|
useTLS: useTLS,
|
|
|
|
|
useTLS: *b.useTLS,
|
|
|
|
|
isDrop: *b.isDrop,
|
|
|
|
|
path: b.path,
|
|
|
|
|
rawQuery: b.rawQuery,
|
|
|
|
|
dataChannel: make(chan []byte, *b.channelSize),
|
|
|
|
|
@@ -155,12 +115,8 @@ func (b *SafeWebsocketClientBuilder) Build(ctx context.Context) (*SafeWebsocketC
|
|
|
|
|
ctx: ctx,
|
|
|
|
|
reconnectCh: make(chan struct{}, 1),
|
|
|
|
|
isConnected: false,
|
|
|
|
|
doneMap: NewSafeMap[string, chan struct{}](),
|
|
|
|
|
writeChan: make(chan Message),
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if b.authenticateFn != nil {
|
|
|
|
|
wsClient.authenticateFn = b.authenticateFn
|
|
|
|
|
doneMap: safemap.NewSafeMap[string, chan struct{}](),
|
|
|
|
|
writeChan: make(chan Message, 1),
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
go wsClient.reconnectHandler()
|
|
|
|
|
@@ -175,25 +131,24 @@ func (b *SafeWebsocketClientBuilder) Build(ctx context.Context) (*SafeWebsocketC
|
|
|
|
|
type SafeWebsocketClient struct {
|
|
|
|
|
baseHost string
|
|
|
|
|
basePort uint16
|
|
|
|
|
isDrop bool
|
|
|
|
|
useTLS bool
|
|
|
|
|
path *string
|
|
|
|
|
rawQuery *string
|
|
|
|
|
|
|
|
|
|
dataChannel chan []byte
|
|
|
|
|
mu *custom_rwmutex.CustomRwMutex
|
|
|
|
|
conn *websocket.Conn
|
|
|
|
|
ctx context.Context
|
|
|
|
|
cancelFuncs []context.CancelFunc
|
|
|
|
|
|
|
|
|
|
ctx context.Context
|
|
|
|
|
Cancel context.CancelFunc
|
|
|
|
|
dataChannel chan []byte
|
|
|
|
|
|
|
|
|
|
reconnectCh chan struct{}
|
|
|
|
|
reconnectChans []chan struct{}
|
|
|
|
|
isConnected bool
|
|
|
|
|
doneMap *SafeMap[string, chan struct{}]
|
|
|
|
|
authenticateFn func(*SafeWebsocketClient) error
|
|
|
|
|
doneMap *safemap.SafeMap[string, chan struct{}]
|
|
|
|
|
|
|
|
|
|
writeChan chan Message
|
|
|
|
|
pongChan chan error
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func (wsClient *SafeWebsocketClient) connect() error {
|
|
|
|
|
@@ -221,120 +176,159 @@ func (wsClient *SafeWebsocketClient) connect() error {
|
|
|
|
|
return fmt.Errorf("failed to connect to %s: %w", wsClient.baseHost, err)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
conn.SetPingHandler(func(pingData string) error {
|
|
|
|
|
if err := conn.WriteMessage(websocket.PongMessage, []byte(pingData)); err != nil {
|
|
|
|
|
if err == websocket.ErrCloseSent {
|
|
|
|
|
return nil
|
|
|
|
|
}
|
|
|
|
|
if netErr, ok := err.(interface{ Timeout() bool }); ok && netErr.Timeout() {
|
|
|
|
|
return nil
|
|
|
|
|
}
|
|
|
|
|
return err
|
|
|
|
|
}
|
|
|
|
|
return nil
|
|
|
|
|
})
|
|
|
|
|
|
|
|
|
|
pingCtx, pingCancel := context.WithCancel(context.Background())
|
|
|
|
|
go wsClient.startPingTicker(pingCtx)
|
|
|
|
|
wsClient.mu.WriteHandler(func() error {
|
|
|
|
|
wsClient.cancelFuncs = append(wsClient.cancelFuncs, pingCancel)
|
|
|
|
|
return nil
|
|
|
|
|
})
|
|
|
|
|
|
|
|
|
|
go wsClient.startPingTicker(pingCtx)
|
|
|
|
|
|
|
|
|
|
if wsClient.conn != nil {
|
|
|
|
|
wsClient.conn.Close()
|
|
|
|
|
}
|
|
|
|
|
wsClient.conn = conn
|
|
|
|
|
wsClient.isConnected = true
|
|
|
|
|
|
|
|
|
|
if wsClient.authenticateFn != nil {
|
|
|
|
|
if err := wsClient.authenticateFn(wsClient); err != nil {
|
|
|
|
|
go wsClient.writePump()
|
|
|
|
|
go wsClient.readPump()
|
|
|
|
|
|
|
|
|
|
conn.SetPingHandler(func(pingData string) error {
|
|
|
|
|
wsClient.writeChan <- Message{
|
|
|
|
|
MessageType: MessageTypePong,
|
|
|
|
|
Data: []byte(pingData),
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
select {
|
|
|
|
|
case err := <-wsClient.pongChan:
|
|
|
|
|
return err
|
|
|
|
|
default:
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
return nil
|
|
|
|
|
})
|
|
|
|
|
|
|
|
|
|
go func() {
|
|
|
|
|
ctx, cancel := context.WithCancel(context.Background())
|
|
|
|
|
wsClient.mu.WriteHandler(func() error {
|
|
|
|
|
wsClient.cancelFuncs = append(wsClient.cancelFuncs, cancel)
|
|
|
|
|
return nil
|
|
|
|
|
})
|
|
|
|
|
return nil
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
writer, err := conn.NextWriter(websocket.TextMessage)
|
|
|
|
|
if err != nil {
|
|
|
|
|
func (wsClient *SafeWebsocketClient) writePump() {
|
|
|
|
|
ctx, cancel := context.WithCancel(context.Background())
|
|
|
|
|
wsClient.mu.WriteHandler(func() error {
|
|
|
|
|
wsClient.cancelFuncs = append(wsClient.cancelFuncs, cancel)
|
|
|
|
|
return nil
|
|
|
|
|
})
|
|
|
|
|
|
|
|
|
|
var c *websocket.Conn
|
|
|
|
|
wsClient.mu.ReadHandler(func() error {
|
|
|
|
|
c = wsClient.conn
|
|
|
|
|
return nil
|
|
|
|
|
})
|
|
|
|
|
|
|
|
|
|
for {
|
|
|
|
|
select {
|
|
|
|
|
case <-ctx.Done():
|
|
|
|
|
log.Println("Writer canceled by context")
|
|
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
for {
|
|
|
|
|
select {
|
|
|
|
|
case <-ctx.Done():
|
|
|
|
|
fmt.Println("Writer stopped due to client shutdown")
|
|
|
|
|
case data := <-wsClient.writeChan:
|
|
|
|
|
if c == nil {
|
|
|
|
|
return
|
|
|
|
|
case data := <-wsClient.writeChan:
|
|
|
|
|
if conn == nil {
|
|
|
|
|
wsClient.triggerReconnect()
|
|
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if _, err := writer.Write(data.Data); err != nil {
|
|
|
|
|
wsClient.triggerReconnect()
|
|
|
|
|
return
|
|
|
|
|
if err := c.WriteMessage(int(data.MessageType), data.Data); err != nil {
|
|
|
|
|
log.Printf("error on write message: %v\n", err)
|
|
|
|
|
if data.MessageType == MessageTypePong {
|
|
|
|
|
wsClient.pongChan <- err
|
|
|
|
|
}
|
|
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}()
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
go func() {
|
|
|
|
|
ctx, cancel := context.WithCancel(context.Background())
|
|
|
|
|
wsClient.mu.WriteHandler(func() error {
|
|
|
|
|
wsClient.cancelFuncs = append(wsClient.cancelFuncs, cancel)
|
|
|
|
|
return nil
|
|
|
|
|
})
|
|
|
|
|
func (wsClient *SafeWebsocketClient) readPump() {
|
|
|
|
|
ctx, cancel := context.WithCancel(context.Background())
|
|
|
|
|
wsClient.mu.WriteHandler(func() error {
|
|
|
|
|
wsClient.cancelFuncs = append(wsClient.cancelFuncs, cancel)
|
|
|
|
|
return nil
|
|
|
|
|
})
|
|
|
|
|
|
|
|
|
|
var c *websocket.Conn
|
|
|
|
|
wsClient.mu.ReadHandler(func() error {
|
|
|
|
|
c = wsClient.conn
|
|
|
|
|
return nil
|
|
|
|
|
})
|
|
|
|
|
|
|
|
|
|
if wsClient.isDrop {
|
|
|
|
|
for {
|
|
|
|
|
select {
|
|
|
|
|
case <-ctx.Done():
|
|
|
|
|
fmt.Println("Reader stopped due to client shutdown")
|
|
|
|
|
log.Println("Reader canceled by context")
|
|
|
|
|
return
|
|
|
|
|
default:
|
|
|
|
|
if conn == nil {
|
|
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
if err := conn.SetReadDeadline(time.Now().Add(readDeadline)); err != nil {
|
|
|
|
|
wsClient.triggerReconnect()
|
|
|
|
|
fmt.Printf("error on read deadline: %v\n", err)
|
|
|
|
|
if c == nil {
|
|
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
mt, reader, err := conn.NextReader()
|
|
|
|
|
if err := c.SetReadDeadline(time.Now().Add(readDeadline)); err != nil {
|
|
|
|
|
log.Printf("error on read deadline: %v\n", err)
|
|
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
messageType, data, err := c.ReadMessage()
|
|
|
|
|
if err != nil {
|
|
|
|
|
log.Printf("error on read message: %v\n", err)
|
|
|
|
|
wsClient.triggerReconnect()
|
|
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if mt != websocket.TextMessage {
|
|
|
|
|
if messageType != websocket.TextMessage {
|
|
|
|
|
continue
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
readerBytes, err := io.ReadAll(reader)
|
|
|
|
|
if err != nil {
|
|
|
|
|
fmt.Printf("io reader failed: %v\n", err)
|
|
|
|
|
wsClient.triggerReconnect()
|
|
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
select {
|
|
|
|
|
case wsClient.dataChannel <- readerBytes:
|
|
|
|
|
case wsClient.dataChannel <- data:
|
|
|
|
|
case <-ctx.Done():
|
|
|
|
|
return
|
|
|
|
|
default:
|
|
|
|
|
fmt.Println("Data channel full, dropping message")
|
|
|
|
|
log.Println("Data channel full, dropping message")
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
} else {
|
|
|
|
|
for {
|
|
|
|
|
select {
|
|
|
|
|
case <-ctx.Done():
|
|
|
|
|
log.Println("Reader canceled by context")
|
|
|
|
|
return
|
|
|
|
|
default:
|
|
|
|
|
if c == nil {
|
|
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if err := c.SetReadDeadline(time.Now().Add(readDeadline)); err != nil {
|
|
|
|
|
log.Printf("error on read deadline: %v\n", err)
|
|
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
messageType, data, err := c.ReadMessage()
|
|
|
|
|
if err != nil {
|
|
|
|
|
log.Printf("error on read message: %v\n", err)
|
|
|
|
|
wsClient.triggerReconnect()
|
|
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if messageType != websocket.TextMessage {
|
|
|
|
|
continue
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
select {
|
|
|
|
|
case wsClient.dataChannel <- data:
|
|
|
|
|
case <-ctx.Done():
|
|
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
}
|
|
|
|
|
}()
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return nil
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func (wsClient *SafeWebsocketClient) startPingTicker(ctx context.Context) {
|
|
|
|
|
@@ -344,12 +338,12 @@ func (wsClient *SafeWebsocketClient) startPingTicker(ctx context.Context) {
|
|
|
|
|
for {
|
|
|
|
|
select {
|
|
|
|
|
case <-ctx.Done():
|
|
|
|
|
log.Println("ping ticker stopped")
|
|
|
|
|
log.Println("ping ticker canceled by context")
|
|
|
|
|
return
|
|
|
|
|
case <-ticker.C:
|
|
|
|
|
wsClient.writeChan <- Message{
|
|
|
|
|
MessageType: websocket.PingMessage,
|
|
|
|
|
Data: nil,
|
|
|
|
|
Data: []byte{},
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
@@ -380,7 +374,7 @@ func (wsClient *SafeWebsocketClient) reconnectHandler() {
|
|
|
|
|
})
|
|
|
|
|
|
|
|
|
|
wsClient.isConnected = false
|
|
|
|
|
time.Sleep(100 * time.Millisecond)
|
|
|
|
|
// time.Sleep(100 * time.Millisecond)
|
|
|
|
|
|
|
|
|
|
isInnerLoop := true
|
|
|
|
|
for isInnerLoop {
|
|
|
|
|
@@ -418,7 +412,7 @@ func (wsClient *SafeWebsocketClient) reconnectHandler() {
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func (wsClient *SafeWebsocketClient) ReconnectChannel() <-chan struct{} {
|
|
|
|
|
reconnectCh := make(chan struct{})
|
|
|
|
|
reconnectCh := make(chan struct{}, 1)
|
|
|
|
|
wsClient.mu.WriteHandler(func() error {
|
|
|
|
|
wsClient.reconnectChans = append(wsClient.reconnectChans, reconnectCh)
|
|
|
|
|
return nil
|
|
|
|
|
@@ -431,6 +425,10 @@ func (wsClient *SafeWebsocketClient) DataChannel() <-chan []byte {
|
|
|
|
|
return wsClient.dataChannel
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func (wsClient *SafeWebsocketClient) CloseDataChannel() {
|
|
|
|
|
close(wsClient.dataChannel)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func (wsClient *SafeWebsocketClient) Write(data []byte) error {
|
|
|
|
|
wsClient.writeChan <- Message{
|
|
|
|
|
MessageType: MessageTypeText,
|
|
|
|
|
|