Compare commits

...

6 Commits

4 changed files with 143 additions and 151 deletions

4
go.mod
View File

@@ -4,4 +4,6 @@ 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 require git.neurocipta.com/rogerferdinan/custom-rwmutex v1.0.0
require git.neurocipta.com/rogerferdinan/safe-map v0.0.0-20251011004629-ab0b119a7c48 // indirect

2
go.sum
View File

@@ -1,4 +1,6 @@
git.neurocipta.com/rogerferdinan/custom-rwmutex v1.0.0 h1:KnNc40SrYsg0cksIIcQy/ca6bunkGADQOs1u7O/E+iY= 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= git.neurocipta.com/rogerferdinan/custom-rwmutex v1.0.0/go.mod h1:9DvvHc2UZhBwEs63NgO4IhiuHnBNtTuBkTJgiMnnCss=
git.neurocipta.com/rogerferdinan/safe-map v0.0.0-20251011004629-ab0b119a7c48 h1:4wXSbEuwFd2gycaaGP35bjUkKEEO6WcVfJ6cetEyT5s=
git.neurocipta.com/rogerferdinan/safe-map v0.0.0-20251011004629-ab0b119a7c48/go.mod h1:QtIxG0BYCCq8a5qyklpSHA8qWUvKr+mfl42qF9QxTc0=
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

@@ -23,9 +23,9 @@ type Client struct {
func NewClient(conn *websocket.Conn, subscribedPath string) *Client { func NewClient(conn *websocket.Conn, subscribedPath string) *Client {
return &Client{ return &Client{
Conn: conn, Conn: conn,
Send: make(chan []byte, 64), Send: make(chan []byte, 2),
SubscribedPath: subscribedPath, SubscribedPath: subscribedPath,
done: make(chan struct{}), done: make(chan struct{}, 1),
} }
} }
@@ -38,10 +38,10 @@ type Hub struct {
func NewHub() *Hub { func NewHub() *Hub {
return &Hub{ return &Hub{
Broadcast: make(chan []byte), Broadcast: make(chan []byte, 1),
Register: make(chan *Client), Register: make(chan *Client, 1),
Unregister: make(chan *Client), Unregister: make(chan *Client, 1),
Clients: make(map[*Client]bool), Clients: make(map[*Client]bool, 1),
} }
} }
@@ -117,7 +117,7 @@ func ReadPump(c *Client, h *Hub) {
for { for {
messageType, message, err := c.Conn.ReadMessage() messageType, message, err := c.Conn.ReadMessage()
if err != nil { if err != nil {
if !websocket.IsUnexpectedCloseError(err, websocket.CloseGoingAway, websocket.CloseAbnormalClosure) { if websocket.IsUnexpectedCloseError(err, websocket.CloseGoingAway, websocket.CloseAbnormalClosure) {
log.Printf("WebSocket error: %v", err) log.Printf("WebSocket error: %v", err)
} }
break break

View File

@@ -6,72 +6,26 @@ import (
"log" "log"
"net/url" "net/url"
"strings" "strings"
"sync"
"time" "time"
custom_rwmutex "git.neurocipta.com/rogerferdinan/custom-rwmutex" custom_rwmutex "git.neurocipta.com/rogerferdinan/custom-rwmutex"
safemap "git.neurocipta.com/rogerferdinan/safe-map"
"git.neurocipta.com/rogerferdinan/safe-web-socket/internal" "git.neurocipta.com/rogerferdinan/safe-web-socket/internal"
"github.com/gorilla/websocket" "github.com/gorilla/websocket"
) )
const ( const (
pingPeriod = 10 * time.Second pingPeriod = 10 * time.Second
readDeadline = 120 * time.Second 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 type MessageType uint
const ( const (
MessageTypeText MessageType = iota + 1 MessageTypeText MessageType = websocket.TextMessage
MessageTypePing MessageType = iota MessageTypePing MessageType = websocket.PingMessage
MessageTypePong MessageType = iota MessageTypePong MessageType = websocket.PongMessage
MessageTypeClose MessageType = iota MessageTypeClose MessageType = websocket.CloseMessage
) )
type Message struct { type Message struct {
@@ -80,13 +34,13 @@ type Message struct {
} }
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"`
path *string path *string
rawQuery *string rawQuery *string
useTLS *bool isDrop *bool
channelSize *int64 useTLS *bool
authenticateFn func(*SafeWebsocketClient) error channelSize *int64
} }
func NewSafeWebsocketClientBuilder() *SafeWebsocketClientBuilder { func NewSafeWebsocketClientBuilder() *SafeWebsocketClientBuilder {
@@ -108,11 +62,6 @@ func (b *SafeWebsocketClientBuilder) UseTLS(useTLS bool) *SafeWebsocketClientBui
return b return b
} }
func (b *SafeWebsocketClientBuilder) AuthenticateFn(authenticateFn func(*SafeWebsocketClient) error) *SafeWebsocketClientBuilder {
b.authenticateFn = authenticateFn
return b
}
func (b *SafeWebsocketClientBuilder) Path(path string) *SafeWebsocketClientBuilder { func (b *SafeWebsocketClientBuilder) Path(path string) *SafeWebsocketClientBuilder {
b.path = &path b.path = &path
return b return b
@@ -123,6 +72,11 @@ func (b *SafeWebsocketClientBuilder) RawQuery(rawQuery string) *SafeWebsocketCli
return b return b
} }
func (b *SafeWebsocketClientBuilder) IsDrop(isDrop bool) *SafeWebsocketClientBuilder {
b.isDrop = &isDrop
return b
}
func (b *SafeWebsocketClientBuilder) ChannelSize(channelSize int64) *SafeWebsocketClientBuilder { func (b *SafeWebsocketClientBuilder) ChannelSize(channelSize int64) *SafeWebsocketClientBuilder {
b.channelSize = &channelSize b.channelSize = &channelSize
return b return b
@@ -133,9 +87,15 @@ func (b *SafeWebsocketClientBuilder) Build(ctx context.Context) (*SafeWebsocketC
return nil, err return nil, err
} }
var useTLS bool // var useTLS bool
if b.useTLS != nil { if b.useTLS == nil {
useTLS = *b.useTLS useTLS := true
b.useTLS = &useTLS
}
if b.isDrop == nil {
isDrop := true
b.isDrop = &isDrop
} }
if b.channelSize == nil { if b.channelSize == nil {
@@ -146,7 +106,8 @@ func (b *SafeWebsocketClientBuilder) Build(ctx context.Context) (*SafeWebsocketC
wsClient := SafeWebsocketClient{ wsClient := SafeWebsocketClient{
baseHost: *b.baseHost, baseHost: *b.baseHost,
basePort: *b.basePort, basePort: *b.basePort,
useTLS: useTLS, useTLS: *b.useTLS,
isDrop: *b.isDrop,
path: b.path, path: b.path,
rawQuery: b.rawQuery, rawQuery: b.rawQuery,
dataChannel: make(chan []byte, *b.channelSize), dataChannel: make(chan []byte, *b.channelSize),
@@ -154,12 +115,8 @@ func (b *SafeWebsocketClientBuilder) Build(ctx context.Context) (*SafeWebsocketC
ctx: ctx, ctx: ctx,
reconnectCh: make(chan struct{}, 1), reconnectCh: make(chan struct{}, 1),
isConnected: false, isConnected: false,
doneMap: NewSafeMap[string, chan struct{}](), doneMap: safemap.NewSafeMap[string, chan struct{}](),
writeChan: make(chan Message), writeChan: make(chan Message, 1),
}
if b.authenticateFn != nil {
wsClient.authenticateFn = b.authenticateFn
} }
go wsClient.reconnectHandler() go wsClient.reconnectHandler()
@@ -174,25 +131,24 @@ func (b *SafeWebsocketClientBuilder) Build(ctx context.Context) (*SafeWebsocketC
type SafeWebsocketClient struct { type SafeWebsocketClient struct {
baseHost string baseHost string
basePort uint16 basePort uint16
isDrop bool
useTLS bool useTLS bool
path *string path *string
rawQuery *string rawQuery *string
dataChannel chan []byte
mu *custom_rwmutex.CustomRwMutex mu *custom_rwmutex.CustomRwMutex
conn *websocket.Conn conn *websocket.Conn
ctx context.Context
cancelFuncs []context.CancelFunc cancelFuncs []context.CancelFunc
dataChannel chan []byte
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.SafeMap[string, chan struct{}]
authenticateFn func(*SafeWebsocketClient) error
writeChan chan Message writeChan chan Message
pongChan chan error
} }
func (wsClient *SafeWebsocketClient) connect() error { func (wsClient *SafeWebsocketClient) connect() error {
@@ -234,68 +190,84 @@ func (wsClient *SafeWebsocketClient) connect() error {
wsClient.conn = conn wsClient.conn = conn
wsClient.isConnected = true wsClient.isConnected = true
if wsClient.authenticateFn != nil { go wsClient.writePump()
if err := wsClient.authenticateFn(wsClient); err != nil { go wsClient.readPump()
return err
conn.SetPingHandler(func(pingData string) error {
wsClient.writeChan <- Message{
MessageType: MessageTypePong,
Data: []byte(pingData),
} }
}
go func() { select {
ctx, cancel := context.WithCancel(context.Background()) case err := <-wsClient.pongChan:
wsClient.mu.WriteHandler(func() error { return err
wsClient.cancelFuncs = append(wsClient.cancelFuncs, cancel) default:
return nil }
}) return nil
})
var c *websocket.Conn return nil
wsClient.mu.ReadHandler(func() error { }
c = conn
return nil
})
for { func (wsClient *SafeWebsocketClient) writePump() {
select { ctx, cancel := context.WithCancel(context.Background())
case <-ctx.Done(): wsClient.mu.WriteHandler(func() error {
log.Println("Writer stopped due to client shutdown") 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
case data := <-wsClient.writeChan:
if c == nil {
return return
case data := <-wsClient.writeChan: }
if c == nil {
wsClient.triggerReconnect()
return
}
if err := c.WriteMessage(int(data.MessageType), data.Data); err != nil { if err := c.WriteMessage(int(data.MessageType), data.Data); err != nil {
log.Printf("error on write message: %v\n", err) log.Printf("error on write message: %v\n", err)
wsClient.triggerReconnect() if data.MessageType == MessageTypePong {
return wsClient.pongChan <- err
} }
return
} }
} }
}() }
}
go func() { func (wsClient *SafeWebsocketClient) readPump() {
ctx, cancel := context.WithCancel(context.Background()) ctx, cancel := context.WithCancel(context.Background())
wsClient.mu.WriteHandler(func() error { wsClient.mu.WriteHandler(func() error {
wsClient.cancelFuncs = append(wsClient.cancelFuncs, cancel) wsClient.cancelFuncs = append(wsClient.cancelFuncs, cancel)
return nil return nil
}) })
var c *websocket.Conn var c *websocket.Conn
wsClient.mu.ReadHandler(func() error {
c = wsClient.conn
return nil
})
wsClient.mu.ReadHandler(func() error { if wsClient.isDrop {
c = conn
return nil
})
if c == nil {
wsClient.triggerReconnect()
return
}
for { for {
select { select {
case <-ctx.Done(): case <-ctx.Done():
log.Println("Reader stopped due to client shutdown") log.Println("Reader canceled by context")
return return
default: default:
if c == nil {
return
}
if err := c.SetReadDeadline(time.Now().Add(readDeadline)); err != nil { if err := c.SetReadDeadline(time.Now().Add(readDeadline)); err != nil {
log.Printf("error on read deadline: %v\n", err) log.Printf("error on read deadline: %v\n", err)
return return
@@ -321,26 +293,42 @@ func (wsClient *SafeWebsocketClient) connect() error {
} }
} }
} }
}() } else {
for {
select {
case <-ctx.Done():
log.Println("Reader canceled by context")
return
default:
if c == nil {
return
}
conn.SetPingHandler(func(pingData string) error { if err := c.SetReadDeadline(time.Now().Add(readDeadline)); err != nil {
// wsClient.writeChan <- Message{ log.Printf("error on read deadline: %v\n", err)
// MessageType: MessageTypePong, return
// Data: []byte(pingData), }
// }
if err := conn.WriteMessage(websocket.PongMessage, []byte(pingData)); err != nil { messageType, data, err := c.ReadMessage()
if err == websocket.ErrCloseSent { if err != nil {
return 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
}
} }
if netErr, ok := err.(interface{ Timeout() bool }); ok && netErr.Timeout() {
return nil
}
return err
} }
return nil }
})
return nil
} }
func (wsClient *SafeWebsocketClient) startPingTicker(ctx context.Context) { func (wsClient *SafeWebsocketClient) startPingTicker(ctx context.Context) {
@@ -386,7 +374,7 @@ func (wsClient *SafeWebsocketClient) reconnectHandler() {
}) })
wsClient.isConnected = false wsClient.isConnected = false
time.Sleep(100 * time.Millisecond) // time.Sleep(100 * time.Millisecond)
isInnerLoop := true isInnerLoop := true
for isInnerLoop { for isInnerLoop {
@@ -424,7 +412,7 @@ func (wsClient *SafeWebsocketClient) reconnectHandler() {
} }
func (wsClient *SafeWebsocketClient) ReconnectChannel() <-chan struct{} { func (wsClient *SafeWebsocketClient) ReconnectChannel() <-chan struct{} {
reconnectCh := make(chan struct{}) reconnectCh := make(chan struct{}, 1)
wsClient.mu.WriteHandler(func() error { wsClient.mu.WriteHandler(func() error {
wsClient.reconnectChans = append(wsClient.reconnectChans, reconnectCh) wsClient.reconnectChans = append(wsClient.reconnectChans, reconnectCh)
return nil return nil