fix: changing to one concurrent writer & reader
This commit is contained in:
@@ -3,6 +3,7 @@ package client
|
|||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
"fmt"
|
"fmt"
|
||||||
|
"io"
|
||||||
"log"
|
"log"
|
||||||
"net/url"
|
"net/url"
|
||||||
"strings"
|
"strings"
|
||||||
@@ -16,6 +17,7 @@ import (
|
|||||||
|
|
||||||
const (
|
const (
|
||||||
pingPeriod = 10 * time.Second
|
pingPeriod = 10 * time.Second
|
||||||
|
readDeadline = 10 * time.Second
|
||||||
)
|
)
|
||||||
|
|
||||||
type SafeMap[K comparable, V any] struct {
|
type SafeMap[K comparable, V any] struct {
|
||||||
@@ -64,6 +66,20 @@ func (sm *SafeMap[K, V]) Len() int {
|
|||||||
return count
|
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 {
|
type SafeWebsocketClientBuilder struct {
|
||||||
baseHost *string `nil_checker:"required"`
|
baseHost *string `nil_checker:"required"`
|
||||||
basePort *uint16 `nil_checker:"required"`
|
basePort *uint16 `nil_checker:"required"`
|
||||||
@@ -161,16 +177,22 @@ type SafeWebsocketClient struct {
|
|||||||
useTLS bool
|
useTLS bool
|
||||||
path *string
|
path *string
|
||||||
rawQuery *string
|
rawQuery *string
|
||||||
|
|
||||||
dataChannel chan []byte
|
dataChannel chan []byte
|
||||||
mu *custom_rwmutex.CustomRwMutex
|
mu *custom_rwmutex.CustomRwMutex
|
||||||
conn *websocket.Conn
|
conn *websocket.Conn
|
||||||
cancelFuncs []context.CancelFunc
|
cancelFuncs []context.CancelFunc
|
||||||
|
|
||||||
ctx context.Context
|
ctx context.Context
|
||||||
|
Cancel context.CancelFunc
|
||||||
|
|
||||||
reconnectCh chan struct{}
|
reconnectCh chan struct{}
|
||||||
reconnectChans []chan struct{}
|
reconnectChans []chan struct{}
|
||||||
isConnected bool
|
isConnected bool
|
||||||
doneMap *SafeMap[string, chan struct{}]
|
doneMap *SafeMap[string, chan struct{}]
|
||||||
authenticateFn func(*SafeWebsocketClient) error
|
authenticateFn func(*SafeWebsocketClient) error
|
||||||
|
|
||||||
|
writeChan chan Message
|
||||||
}
|
}
|
||||||
|
|
||||||
func (wsClient *SafeWebsocketClient) connect() error {
|
func (wsClient *SafeWebsocketClient) connect() error {
|
||||||
@@ -211,6 +233,10 @@ func (wsClient *SafeWebsocketClient) connect() error {
|
|||||||
return nil
|
return nil
|
||||||
})
|
})
|
||||||
|
|
||||||
|
pingCtx, pingCancel := context.WithCancel(context.Background())
|
||||||
|
go wsClient.startPingTicker(pingCtx)
|
||||||
|
wsClient.cancelFuncs = append(wsClient.cancelFuncs, pingCancel)
|
||||||
|
|
||||||
if wsClient.conn != nil {
|
if wsClient.conn != nil {
|
||||||
wsClient.conn.Close()
|
wsClient.conn.Close()
|
||||||
}
|
}
|
||||||
@@ -223,17 +249,82 @@ func (wsClient *SafeWebsocketClient) connect() error {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
wsClient.mu.WriteHandler(func() error {
|
go func() {
|
||||||
pingCtx, pingCancel := context.WithCancel(context.Background())
|
ctx, cancel := context.WithCancel(context.Background())
|
||||||
go wsClient.startPingTicker(pingCtx)
|
wsClient.cancelFuncs = append(wsClient.cancelFuncs, cancel)
|
||||||
wsClient.cancelFuncs = append(wsClient.cancelFuncs, pingCancel)
|
for {
|
||||||
|
select {
|
||||||
|
case <-ctx.Done():
|
||||||
|
fmt.Println("Writer stopped due to client shutdown")
|
||||||
|
return
|
||||||
|
case data := <-wsClient.writeChan:
|
||||||
|
if conn == nil {
|
||||||
|
wsClient.triggerReconnect()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
messageType := websocket.TextMessage
|
||||||
|
switch data.MessageType {
|
||||||
|
case MessageTypePing:
|
||||||
|
messageType = websocket.PingMessage
|
||||||
|
case MessageTypePong:
|
||||||
|
messageType = websocket.PongMessage
|
||||||
|
case MessageTypeClose:
|
||||||
|
messageType = websocket.CloseMessage
|
||||||
|
}
|
||||||
|
writer, err := conn.NextWriter(messageType)
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
receiverCtx, receiverCancel := context.WithCancel(context.Background())
|
if _, err := writer.Write(data.Data); err != nil {
|
||||||
go wsClient.startReceiveHandler(receiverCtx)
|
return
|
||||||
wsClient.cancelFuncs = append(wsClient.cancelFuncs, receiverCancel)
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
|
||||||
|
go func() {
|
||||||
|
ctx, cancel := context.WithCancel(context.Background())
|
||||||
|
wsClient.cancelFuncs = append(wsClient.cancelFuncs, cancel)
|
||||||
|
for {
|
||||||
|
select {
|
||||||
|
case <-ctx.Done():
|
||||||
|
fmt.Println("Reader stopped due to client shutdown")
|
||||||
|
return
|
||||||
|
default:
|
||||||
|
if conn == nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if err := conn.SetReadDeadline(time.Now().Add(readDeadline)); err != nil {
|
||||||
|
fmt.Printf("error on read deadline: %v\n", err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
_, reader, err := conn.NextReader()
|
||||||
|
if err != nil {
|
||||||
|
fmt.Printf("Next Reader Closed: %v\n", err)
|
||||||
|
wsClient.triggerReconnect()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
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 <-ctx.Done():
|
||||||
|
return
|
||||||
|
default:
|
||||||
|
fmt.Println("Data channel full, dropping message")
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
|
||||||
return nil
|
|
||||||
})
|
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -247,53 +338,47 @@ func (wsClient *SafeWebsocketClient) startPingTicker(ctx context.Context) {
|
|||||||
log.Println("ping ticker stopped")
|
log.Println("ping ticker stopped")
|
||||||
return
|
return
|
||||||
case <-ticker.C:
|
case <-ticker.C:
|
||||||
wsClient.mu.WriteHandler(func() error {
|
wsClient.writeChan <- Message{
|
||||||
if wsClient.conn == nil {
|
MessageType: websocket.PingMessage,
|
||||||
return fmt.Errorf("connection closed")
|
Data: nil,
|
||||||
}
|
}
|
||||||
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) {
|
// func (wsClient *SafeWebsocketClient) startReceiveHandler(ctx context.Context) {
|
||||||
for {
|
// for {
|
||||||
select {
|
// select {
|
||||||
case <-ctx.Done():
|
// case <-ctx.Done():
|
||||||
log.Println("receive handler stopped")
|
// log.Println("receive handler stopped")
|
||||||
return
|
// return
|
||||||
default:
|
// default:
|
||||||
if err := wsClient.mu.ReadHandler(func() error {
|
// if err := wsClient.mu.ReadHandler(func() error {
|
||||||
conn := wsClient.conn
|
// conn := wsClient.conn
|
||||||
|
|
||||||
if conn == nil {
|
// if conn == nil {
|
||||||
wsClient.triggerReconnect()
|
// wsClient.triggerReconnect()
|
||||||
return fmt.Errorf("connection closed")
|
// return fmt.Errorf("connection closed")
|
||||||
}
|
// }
|
||||||
_, message, err := conn.ReadMessage()
|
// _, message, err := conn.ReadMessage()
|
||||||
if err != nil {
|
// if err != nil {
|
||||||
wsClient.triggerReconnect()
|
// wsClient.triggerReconnect()
|
||||||
return fmt.Errorf("failed to read message: %v", err)
|
// return fmt.Errorf("failed to read message: %v", err)
|
||||||
}
|
// }
|
||||||
select {
|
// select {
|
||||||
case wsClient.dataChannel <- message:
|
// case wsClient.dataChannel <- message:
|
||||||
case <-ctx.Done():
|
// case <-ctx.Done():
|
||||||
log.Println("Reconnect handler stopped")
|
// log.Println("Reconnect handler stopped")
|
||||||
default:
|
// default:
|
||||||
log.Println("Data channel full, dropping message")
|
// log.Println("")
|
||||||
}
|
// }
|
||||||
return nil
|
// return nil
|
||||||
}); err != nil {
|
// }); err != nil {
|
||||||
return
|
// return
|
||||||
}
|
// }
|
||||||
}
|
// }
|
||||||
}
|
// }
|
||||||
}
|
// }
|
||||||
|
|
||||||
func (wsClient *SafeWebsocketClient) triggerReconnect() {
|
func (wsClient *SafeWebsocketClient) triggerReconnect() {
|
||||||
select {
|
select {
|
||||||
@@ -309,6 +394,7 @@ func (wsClient *SafeWebsocketClient) reconnectHandler() {
|
|||||||
select {
|
select {
|
||||||
case <-wsClient.reconnectCh:
|
case <-wsClient.reconnectCh:
|
||||||
log.Println("Reconnect triggered")
|
log.Println("Reconnect triggered")
|
||||||
|
|
||||||
if wsClient.cancelFuncs != nil {
|
if wsClient.cancelFuncs != nil {
|
||||||
for _, cancel := range wsClient.cancelFuncs {
|
for _, cancel := range wsClient.cancelFuncs {
|
||||||
cancel()
|
cancel()
|
||||||
@@ -334,6 +420,8 @@ func (wsClient *SafeWebsocketClient) reconnectHandler() {
|
|||||||
isInnerLoop = false
|
isInnerLoop = false
|
||||||
continue
|
continue
|
||||||
case <-wsClient.ctx.Done():
|
case <-wsClient.ctx.Done():
|
||||||
|
log.Println("reconnect handler stopped due to client shutdown")
|
||||||
|
wsClient.Close()
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -364,14 +452,15 @@ func (wsClient *SafeWebsocketClient) DataChannel() <-chan []byte {
|
|||||||
return wsClient.dataChannel
|
return wsClient.dataChannel
|
||||||
}
|
}
|
||||||
|
|
||||||
func (wsClient *SafeWebsocketClient) WriteJSON(message any) error {
|
func (wsClient *SafeWebsocketClient) Write(data []byte) error {
|
||||||
return wsClient.mu.WriteHandler(func() error {
|
wsClient.writeChan <- Message{
|
||||||
return wsClient.conn.WriteJSON(message)
|
MessageType: MessageTypeText,
|
||||||
})
|
Data: data,
|
||||||
|
}
|
||||||
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (wsClient *SafeWebsocketClient) Close() error {
|
func (wsClient *SafeWebsocketClient) Close() error {
|
||||||
wsClient.mu.WriteHandler(func() error {
|
|
||||||
if wsClient.cancelFuncs != nil {
|
if wsClient.cancelFuncs != nil {
|
||||||
for _, cancel := range wsClient.cancelFuncs {
|
for _, cancel := range wsClient.cancelFuncs {
|
||||||
cancel()
|
cancel()
|
||||||
@@ -387,8 +476,6 @@ func (wsClient *SafeWebsocketClient) Close() error {
|
|||||||
wsClient.conn.Close()
|
wsClient.conn.Close()
|
||||||
}
|
}
|
||||||
wsClient.isConnected = false
|
wsClient.isConnected = false
|
||||||
return nil
|
|
||||||
})
|
|
||||||
close(wsClient.dataChannel)
|
close(wsClient.dataChannel)
|
||||||
|
|
||||||
return nil
|
return nil
|
||||||
|
|||||||
@@ -43,6 +43,7 @@ func main() {
|
|||||||
dataChannel := wsClient.DataChannel()
|
dataChannel := wsClient.DataChannel()
|
||||||
|
|
||||||
for data := range dataChannel {
|
for data := range dataChannel {
|
||||||
|
// _ = data
|
||||||
fmt.Println(string(data))
|
fmt.Println(string(data))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user