|
|
|
|
@@ -15,7 +15,8 @@ import (
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
const (
|
|
|
|
|
pingPeriod = 10 * time.Second
|
|
|
|
|
pingPeriod = 10 * time.Second
|
|
|
|
|
readDeadline = 120 * time.Second
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
type SafeMap[K comparable, V any] struct {
|
|
|
|
|
@@ -64,6 +65,20 @@ func (sm *SafeMap[K, V]) Len() int {
|
|
|
|
|
return count
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
type MessageType uint
|
|
|
|
|
|
|
|
|
|
const (
|
|
|
|
|
MessageTypeText MessageType = iota + 1
|
|
|
|
|
MessageTypePing MessageType = iota
|
|
|
|
|
MessageTypePong MessageType = iota
|
|
|
|
|
MessageTypeClose MessageType = iota
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
type Message struct {
|
|
|
|
|
MessageType MessageType
|
|
|
|
|
Data []byte
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
type SafeWebsocketClientBuilder struct {
|
|
|
|
|
baseHost *string `nil_checker:"required"`
|
|
|
|
|
basePort *uint16 `nil_checker:"required"`
|
|
|
|
|
@@ -140,6 +155,7 @@ func (b *SafeWebsocketClientBuilder) Build(ctx context.Context) (*SafeWebsocketC
|
|
|
|
|
reconnectCh: make(chan struct{}, 1),
|
|
|
|
|
isConnected: false,
|
|
|
|
|
doneMap: NewSafeMap[string, chan struct{}](),
|
|
|
|
|
writeChan: make(chan Message),
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if b.authenticateFn != nil {
|
|
|
|
|
@@ -156,21 +172,27 @@ func (b *SafeWebsocketClientBuilder) Build(ctx context.Context) (*SafeWebsocketC
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
type SafeWebsocketClient struct {
|
|
|
|
|
baseHost string
|
|
|
|
|
basePort uint16
|
|
|
|
|
useTLS bool
|
|
|
|
|
path *string
|
|
|
|
|
rawQuery *string
|
|
|
|
|
dataChannel chan []byte
|
|
|
|
|
mu *custom_rwmutex.CustomRwMutex
|
|
|
|
|
conn *websocket.Conn
|
|
|
|
|
cancelFuncs []context.CancelFunc
|
|
|
|
|
ctx context.Context
|
|
|
|
|
baseHost string
|
|
|
|
|
basePort uint16
|
|
|
|
|
useTLS bool
|
|
|
|
|
path *string
|
|
|
|
|
rawQuery *string
|
|
|
|
|
|
|
|
|
|
dataChannel chan []byte
|
|
|
|
|
mu *custom_rwmutex.CustomRwMutex
|
|
|
|
|
conn *websocket.Conn
|
|
|
|
|
cancelFuncs []context.CancelFunc
|
|
|
|
|
|
|
|
|
|
ctx context.Context
|
|
|
|
|
Cancel context.CancelFunc
|
|
|
|
|
|
|
|
|
|
reconnectCh chan struct{}
|
|
|
|
|
reconnectChans []chan struct{}
|
|
|
|
|
isConnected bool
|
|
|
|
|
doneMap *SafeMap[string, chan struct{}]
|
|
|
|
|
authenticateFn func(*SafeWebsocketClient) error
|
|
|
|
|
|
|
|
|
|
writeChan chan Message
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func (wsClient *SafeWebsocketClient) connect() error {
|
|
|
|
|
@@ -198,19 +220,14 @@ 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
|
|
|
|
|
}
|
|
|
|
|
pingCtx, pingCancel := context.WithCancel(context.Background())
|
|
|
|
|
wsClient.mu.WriteHandler(func() error {
|
|
|
|
|
wsClient.cancelFuncs = append(wsClient.cancelFuncs, pingCancel)
|
|
|
|
|
return nil
|
|
|
|
|
})
|
|
|
|
|
|
|
|
|
|
go wsClient.startPingTicker(pingCtx)
|
|
|
|
|
|
|
|
|
|
if wsClient.conn != nil {
|
|
|
|
|
wsClient.conn.Close()
|
|
|
|
|
}
|
|
|
|
|
@@ -223,17 +240,106 @@ func (wsClient *SafeWebsocketClient) connect() error {
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
wsClient.mu.WriteHandler(func() error {
|
|
|
|
|
pingCtx, pingCancel := context.WithCancel(context.Background())
|
|
|
|
|
go wsClient.startPingTicker(pingCtx)
|
|
|
|
|
wsClient.cancelFuncs = append(wsClient.cancelFuncs, pingCancel)
|
|
|
|
|
go func() {
|
|
|
|
|
ctx, cancel := context.WithCancel(context.Background())
|
|
|
|
|
wsClient.mu.WriteHandler(func() error {
|
|
|
|
|
wsClient.cancelFuncs = append(wsClient.cancelFuncs, cancel)
|
|
|
|
|
return nil
|
|
|
|
|
})
|
|
|
|
|
|
|
|
|
|
receiverCtx, receiverCancel := context.WithCancel(context.Background())
|
|
|
|
|
go wsClient.startReceiveHandler(receiverCtx)
|
|
|
|
|
wsClient.cancelFuncs = append(wsClient.cancelFuncs, receiverCancel)
|
|
|
|
|
var c *websocket.Conn
|
|
|
|
|
wsClient.mu.ReadHandler(func() error {
|
|
|
|
|
c = conn
|
|
|
|
|
return nil
|
|
|
|
|
})
|
|
|
|
|
|
|
|
|
|
for {
|
|
|
|
|
select {
|
|
|
|
|
case <-ctx.Done():
|
|
|
|
|
log.Println("Writer stopped due to client shutdown")
|
|
|
|
|
return
|
|
|
|
|
case data := <-wsClient.writeChan:
|
|
|
|
|
if c == nil {
|
|
|
|
|
wsClient.triggerReconnect()
|
|
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if err := c.WriteMessage(int(data.MessageType), data.Data); err != nil {
|
|
|
|
|
log.Printf("error on write message: %v\n", err)
|
|
|
|
|
wsClient.triggerReconnect()
|
|
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}()
|
|
|
|
|
|
|
|
|
|
go func() {
|
|
|
|
|
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 = conn
|
|
|
|
|
return nil
|
|
|
|
|
})
|
|
|
|
|
if c == nil {
|
|
|
|
|
wsClient.triggerReconnect()
|
|
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
for {
|
|
|
|
|
select {
|
|
|
|
|
case <-ctx.Done():
|
|
|
|
|
log.Println("Reader stopped due to client shutdown")
|
|
|
|
|
return
|
|
|
|
|
default:
|
|
|
|
|
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
|
|
|
|
|
default:
|
|
|
|
|
log.Println("Data channel full, dropping message")
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}()
|
|
|
|
|
|
|
|
|
|
conn.SetPingHandler(func(pingData string) error {
|
|
|
|
|
wsClient.writeChan <- Message{
|
|
|
|
|
MessageType: MessageTypePong,
|
|
|
|
|
Data: []byte(pingData),
|
|
|
|
|
}
|
|
|
|
|
// 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
|
|
|
|
|
})
|
|
|
|
|
|
|
|
|
|
return nil
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
@@ -247,49 +353,9 @@ func (wsClient *SafeWebsocketClient) startPingTicker(ctx context.Context) {
|
|
|
|
|
log.Println("ping ticker stopped")
|
|
|
|
|
return
|
|
|
|
|
case <-ticker.C:
|
|
|
|
|
wsClient.mu.WriteHandler(func() error {
|
|
|
|
|
if wsClient.conn == nil {
|
|
|
|
|
return fmt.Errorf("connection closed")
|
|
|
|
|
}
|
|
|
|
|
if err := wsClient.conn.WriteMessage(websocket.PingMessage, []byte{}); err != nil {
|
|
|
|
|
log.Printf("Ping failed: %v. Will attempt reconnect.", err)
|
|
|
|
|
wsClient.triggerReconnect()
|
|
|
|
|
}
|
|
|
|
|
return nil
|
|
|
|
|
})
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func (wsClient *SafeWebsocketClient) startReceiveHandler(ctx context.Context) {
|
|
|
|
|
for {
|
|
|
|
|
select {
|
|
|
|
|
case <-ctx.Done():
|
|
|
|
|
log.Println("receive handler stopped")
|
|
|
|
|
return
|
|
|
|
|
default:
|
|
|
|
|
if err := wsClient.mu.ReadHandler(func() error {
|
|
|
|
|
conn := wsClient.conn
|
|
|
|
|
|
|
|
|
|
if conn == nil {
|
|
|
|
|
wsClient.triggerReconnect()
|
|
|
|
|
return fmt.Errorf("connection closed")
|
|
|
|
|
}
|
|
|
|
|
_, message, err := conn.ReadMessage()
|
|
|
|
|
if err != nil {
|
|
|
|
|
wsClient.triggerReconnect()
|
|
|
|
|
return fmt.Errorf("failed to read message: %v", err)
|
|
|
|
|
}
|
|
|
|
|
select {
|
|
|
|
|
case wsClient.dataChannel <- message:
|
|
|
|
|
case <-ctx.Done():
|
|
|
|
|
log.Println("Reconnect handler stopped")
|
|
|
|
|
default:
|
|
|
|
|
log.Println("Data channel full, dropping message")
|
|
|
|
|
}
|
|
|
|
|
return nil
|
|
|
|
|
}); err != nil {
|
|
|
|
|
return
|
|
|
|
|
wsClient.writeChan <- Message{
|
|
|
|
|
MessageType: websocket.PingMessage,
|
|
|
|
|
Data: []byte{},
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
@@ -309,11 +375,16 @@ func (wsClient *SafeWebsocketClient) reconnectHandler() {
|
|
|
|
|
select {
|
|
|
|
|
case <-wsClient.reconnectCh:
|
|
|
|
|
log.Println("Reconnect triggered")
|
|
|
|
|
if wsClient.cancelFuncs != nil {
|
|
|
|
|
for _, cancel := range wsClient.cancelFuncs {
|
|
|
|
|
cancel()
|
|
|
|
|
|
|
|
|
|
wsClient.mu.ReadHandler(func() error {
|
|
|
|
|
if wsClient.cancelFuncs != nil {
|
|
|
|
|
for _, cancel := range wsClient.cancelFuncs {
|
|
|
|
|
cancel()
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
return nil
|
|
|
|
|
})
|
|
|
|
|
|
|
|
|
|
wsClient.isConnected = false
|
|
|
|
|
time.Sleep(100 * time.Millisecond)
|
|
|
|
|
|
|
|
|
|
@@ -334,6 +405,8 @@ func (wsClient *SafeWebsocketClient) reconnectHandler() {
|
|
|
|
|
isInnerLoop = false
|
|
|
|
|
continue
|
|
|
|
|
case <-wsClient.ctx.Done():
|
|
|
|
|
log.Println("reconnect handler stopped due to client shutdown")
|
|
|
|
|
wsClient.Close()
|
|
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
@@ -364,32 +437,34 @@ func (wsClient *SafeWebsocketClient) DataChannel() <-chan []byte {
|
|
|
|
|
return wsClient.dataChannel
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func (wsClient *SafeWebsocketClient) WriteJSON(message any) error {
|
|
|
|
|
return wsClient.mu.WriteHandler(func() error {
|
|
|
|
|
return wsClient.conn.WriteJSON(message)
|
|
|
|
|
})
|
|
|
|
|
func (wsClient *SafeWebsocketClient) Write(data []byte) error {
|
|
|
|
|
wsClient.writeChan <- Message{
|
|
|
|
|
MessageType: MessageTypeText,
|
|
|
|
|
Data: data,
|
|
|
|
|
}
|
|
|
|
|
return nil
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func (wsClient *SafeWebsocketClient) Close() error {
|
|
|
|
|
wsClient.mu.WriteHandler(func() error {
|
|
|
|
|
wsClient.mu.ReadHandler(func() error {
|
|
|
|
|
if wsClient.cancelFuncs != nil {
|
|
|
|
|
for _, cancel := range wsClient.cancelFuncs {
|
|
|
|
|
cancel()
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if wsClient.reconnectChans != nil {
|
|
|
|
|
for _, reconnectChan := range wsClient.reconnectChans {
|
|
|
|
|
close(reconnectChan)
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
if wsClient.conn != nil {
|
|
|
|
|
wsClient.conn.Close()
|
|
|
|
|
}
|
|
|
|
|
wsClient.isConnected = false
|
|
|
|
|
return nil
|
|
|
|
|
})
|
|
|
|
|
close(wsClient.dataChannel)
|
|
|
|
|
|
|
|
|
|
if wsClient.reconnectChans != nil {
|
|
|
|
|
for _, reconnectChan := range wsClient.reconnectChans {
|
|
|
|
|
close(reconnectChan)
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
if wsClient.conn != nil {
|
|
|
|
|
wsClient.conn.Close()
|
|
|
|
|
}
|
|
|
|
|
wsClient.isConnected = false
|
|
|
|
|
// close(wsClient.dataChannel)
|
|
|
|
|
|
|
|
|
|
return nil
|
|
|
|
|
}
|
|
|
|
|
|