Compare commits

...

3 Commits

Author SHA1 Message Date
6fb7cea1fa fix client & server experimental fix 2025-09-26 15:02:54 +07:00
7457604e0f fix: client data race hotfix 2025-09-26 14:18:53 +07:00
f32d97eac4 chore: cleaning unused mutex 2025-09-26 09:16:35 +07:00
5 changed files with 48 additions and 71 deletions

2
go.mod
View File

@@ -3,3 +3,5 @@ module git.neurocipta.com/rogerferdinan/safe-web-socket
go 1.24.5 go 1.24.5
require github.com/gorilla/websocket v1.5.3 require github.com/gorilla/websocket v1.5.3
require git.neurocipta.com/rogerferdinan/custom-rwmutex v1.0.0 // indirect

2
go.sum
View File

@@ -1,2 +1,4 @@
git.neurocipta.com/rogerferdinan/custom-rwmutex v1.0.0 h1:KnNc40SrYsg0cksIIcQy/ca6bunkGADQOs1u7O/E+iY=
git.neurocipta.com/rogerferdinan/custom-rwmutex v1.0.0/go.mod h1:9DvvHc2UZhBwEs63NgO4IhiuHnBNtTuBkTJgiMnnCss=
github.com/gorilla/websocket v1.5.3 h1:saDtZ6Pbx/0u+bgYQ3q96pZgCzfhKXGPqt7kZ72aNNg= github.com/gorilla/websocket v1.5.3 h1:saDtZ6Pbx/0u+bgYQ3q96pZgCzfhKXGPqt7kZ72aNNg=
github.com/gorilla/websocket v1.5.3/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE= github.com/gorilla/websocket v1.5.3/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE=

View File

@@ -11,7 +11,7 @@ import (
const ( const (
writeWait = 10 * time.Second writeWait = 10 * time.Second
pongWait = 60 * time.Second pongWait = 60 * time.Second
pingPeriod = 55 * time.Second pingPeriod = 25 * time.Second
) )
type Client struct { type Client struct {
@@ -19,7 +19,6 @@ type Client struct {
Send chan []byte Send chan []byte
SubscribedPath string SubscribedPath string
done chan struct{} done chan struct{}
mu *CustomRwMutex
} }
func NewClient(conn *websocket.Conn, subscribedPath string) *Client { func NewClient(conn *websocket.Conn, subscribedPath string) *Client {
@@ -28,7 +27,6 @@ func NewClient(conn *websocket.Conn, subscribedPath string) *Client {
Send: make(chan []byte, 64), Send: make(chan []byte, 64),
SubscribedPath: subscribedPath, SubscribedPath: subscribedPath,
done: make(chan struct{}), done: make(chan struct{}),
mu: NewCustomRwMutex(),
} }
} }
@@ -37,8 +35,6 @@ type Hub struct {
Broadcast chan []byte Broadcast chan []byte
Register chan *Client Register chan *Client
Unregister chan *Client Unregister chan *Client
writeMu *CustomRwMutex
readMu *CustomRwMutex
} }
func NewHub() *Hub { func NewHub() *Hub {
@@ -47,7 +43,6 @@ func NewHub() *Hub {
Register: make(chan *Client), Register: make(chan *Client),
Unregister: make(chan *Client), Unregister: make(chan *Client),
Clients: make(map[*Client]bool), Clients: make(map[*Client]bool),
writeMu: NewCustomRwMutex(),
} }
} }
@@ -100,7 +95,7 @@ func WritePump(c *Client, h *Hub) {
} }
case <-pingTicker.C: case <-pingTicker.C:
c.Conn.SetWriteDeadline(time.Now().Add(writeWait)) c.Conn.SetWriteDeadline(time.Now().Add(writeWait))
if err := c.Conn.WriteMessage(websocket.PingMessage, nil); err != nil { if err := c.Conn.WriteMessage(websocket.PingMessage, []byte{}); err != nil {
return return
} }
} }

View File

@@ -1,33 +0,0 @@
package internal
import (
"sync"
)
type CustomRwMutex struct {
mu *sync.RWMutex
}
func NewCustomRwMutex() *CustomRwMutex {
return &CustomRwMutex{
mu: &sync.RWMutex{},
}
}
func (rwMu *CustomRwMutex) WriteHandler(fn func() error) error {
rwMu.mu.Lock()
defer rwMu.mu.Unlock()
if err := fn(); err != nil {
return err
}
return nil
}
func (rwMu *CustomRwMutex) ReadHandler(fn func() error) error {
rwMu.mu.RLock()
defer rwMu.mu.RUnlock()
if err := fn(); err != nil {
return err
}
return nil
}

View File

@@ -8,6 +8,7 @@ import (
"strings" "strings"
"time" "time"
custom_rwmutex "git.neurocipta.com/rogerferdinan/custom-rwmutex"
"git.neurocipta.com/rogerferdinan/safe-web-socket/internal" "git.neurocipta.com/rogerferdinan/safe-web-socket/internal"
"github.com/gorilla/websocket" "github.com/gorilla/websocket"
) )
@@ -58,8 +59,6 @@ func (b *SafeWebsocketClientBuilder) Build() (*SafeWebsocketClient, error) {
return nil, err return nil, err
} }
ctx, cancel := context.WithCancel(context.Background())
var useTLS bool var useTLS bool
if b.useTLS != nil { if b.useTLS != nil {
useTLS = *b.useTLS useTLS = *b.useTLS
@@ -71,16 +70,13 @@ func (b *SafeWebsocketClientBuilder) Build() (*SafeWebsocketClient, error) {
useTLS: useTLS, useTLS: useTLS,
path: b.path, path: b.path,
rawQuery: b.rawQuery, rawQuery: b.rawQuery,
ctx: ctx,
cancel: cancel,
dataChannel: make(chan []byte, 1), dataChannel: make(chan []byte, 1),
mu: internal.NewCustomRwMutex(), mu: custom_rwmutex.NewCustomRwMutex(),
reconnectCh: make(chan struct{}, 1), reconnectCh: make(chan struct{}, 1),
isConnected: false, isConnected: false,
} }
if err := wsClient.connect(); err != nil { if err := wsClient.connect(); err != nil {
cancel()
return nil, fmt.Errorf("failed to establish initial connection: %v", err) return nil, fmt.Errorf("failed to establish initial connection: %v", err)
} }
@@ -94,7 +90,7 @@ type SafeWebsocketClient struct {
path *string path *string
rawQuery *string rawQuery *string
dataChannel chan []byte dataChannel chan []byte
mu *internal.CustomRwMutex mu *custom_rwmutex.CustomRwMutex
conn *websocket.Conn conn *websocket.Conn
ctx context.Context ctx context.Context
cancel context.CancelFunc cancel context.CancelFunc
@@ -128,21 +124,27 @@ func (wsClient *SafeWebsocketClient) connect() error {
} }
conn.SetPingHandler(func(pingData string) error { conn.SetPingHandler(func(pingData string) error {
if err := conn.WriteMessage(websocket.PongMessage, []byte(pingData)); err != nil { return wsClient.mu.WriteHandler(func() error {
if err == websocket.ErrCloseSent { if err := conn.WriteMessage(websocket.PongMessage, []byte(pingData)); err != nil {
return nil if err == websocket.ErrCloseSent {
return nil
}
if netErr, ok := err.(interface{ Timeout() bool }); ok && netErr.Timeout() {
return nil
}
return err
} }
if netErr, ok := err.(interface{ Timeout() bool }); ok && netErr.Timeout() { return nil
return nil })
}
return err
}
return nil
}) })
wsClient.mu.WriteHandler(func() error { wsClient.mu.WriteHandler(func() error {
ctx, cancel := context.WithCancel(context.Background())
wsClient.ctx = ctx
wsClient.cancel = cancel
wsClient.conn = conn wsClient.conn = conn
wsClient.isConnected = true wsClient.isConnected = true
return nil return nil
}) })
@@ -176,27 +178,30 @@ func (wsClient *SafeWebsocketClient) startPingTicker() {
func (wsClient *SafeWebsocketClient) startReceiveHandler() { func (wsClient *SafeWebsocketClient) startReceiveHandler() {
for { for {
select { select {
case <-wsClient.reconnectCh:
case <-wsClient.ctx.Done(): case <-wsClient.ctx.Done():
log.Println("Reconnect handler stopped") log.Println("Reconnect handler stopped")
return return
default: default:
if err := wsClient.mu.WriteHandler(func() error { // if err := wsClient.mu.ReadHandler(func() error {
conn := wsClient.conn conn := wsClient.conn
if conn == nil { if conn == nil {
return fmt.Errorf("no active connection, waiting for reconnect")
}
_, message, err := conn.ReadMessage()
if err != nil {
return err
}
wsClient.dataChannel <- message
return nil
}); err != nil {
wsClient.triggerReconnect() wsClient.triggerReconnect()
return return
// return fmt.Errorf("no active connection, waiting for reconnect")
} }
_, message, err := conn.ReadMessage()
if err != nil {
wsClient.triggerReconnect()
return
// return err
}
wsClient.dataChannel <- message
// return nil
// }); err != nil {
// wsClient.triggerReconnect()
// return
// }
} }
} }
} }
@@ -209,8 +214,14 @@ func (wsClient *SafeWebsocketClient) triggerReconnect() {
} }
func (wsClient *SafeWebsocketClient) reconnectHandler() { func (wsClient *SafeWebsocketClient) reconnectHandler() {
for range wsClient.reconnectCh { for {
wsClient.connect() select {
case <-wsClient.reconnectCh:
wsClient.cancel()
wsClient.connect()
case <-wsClient.ctx.Done():
return
}
} }
} }