Compare commits
10 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 9d74e72ede | |||
| dfbe2f2808 | |||
| 4792d638c1 | |||
| b96e574726 | |||
| 752804cc58 | |||
| e686e69a24 | |||
| 034e5b68e0 | |||
| 6fb7cea1fa | |||
| 7457604e0f | |||
| f32d97eac4 |
2
go.mod
2
go.mod
@@ -3,3 +3,5 @@ module git.neurocipta.com/rogerferdinan/safe-web-socket
|
||||
go 1.24.5
|
||||
|
||||
require github.com/gorilla/websocket v1.5.3
|
||||
|
||||
require git.neurocipta.com/rogerferdinan/custom-rwmutex v1.0.0 // indirect
|
||||
|
||||
2
go.sum
2
go.sum
@@ -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/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE=
|
||||
|
||||
@@ -11,7 +11,7 @@ import (
|
||||
const (
|
||||
writeWait = 10 * time.Second
|
||||
pongWait = 60 * time.Second
|
||||
pingPeriod = 55 * time.Second
|
||||
pingPeriod = 25 * time.Second
|
||||
)
|
||||
|
||||
type Client struct {
|
||||
@@ -19,7 +19,6 @@ type Client struct {
|
||||
Send chan []byte
|
||||
SubscribedPath string
|
||||
done chan struct{}
|
||||
mu *CustomRwMutex
|
||||
}
|
||||
|
||||
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),
|
||||
SubscribedPath: subscribedPath,
|
||||
done: make(chan struct{}),
|
||||
mu: NewCustomRwMutex(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -37,8 +35,6 @@ type Hub struct {
|
||||
Broadcast chan []byte
|
||||
Register chan *Client
|
||||
Unregister chan *Client
|
||||
writeMu *CustomRwMutex
|
||||
readMu *CustomRwMutex
|
||||
}
|
||||
|
||||
func NewHub() *Hub {
|
||||
@@ -47,7 +43,6 @@ func NewHub() *Hub {
|
||||
Register: make(chan *Client),
|
||||
Unregister: make(chan *Client),
|
||||
Clients: make(map[*Client]bool),
|
||||
writeMu: NewCustomRwMutex(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -100,7 +95,7 @@ func WritePump(c *Client, h *Hub) {
|
||||
}
|
||||
case <-pingTicker.C:
|
||||
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
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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
|
||||
}
|
||||
@@ -6,8 +6,10 @@ import (
|
||||
"log"
|
||||
"net/url"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
custom_rwmutex "git.neurocipta.com/rogerferdinan/custom-rwmutex"
|
||||
"git.neurocipta.com/rogerferdinan/safe-web-socket/internal"
|
||||
"github.com/gorilla/websocket"
|
||||
)
|
||||
@@ -16,12 +18,59 @@ const (
|
||||
pingPeriod = 10 * 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 SafeWebsocketClientBuilder struct {
|
||||
baseHost *string `nil_checker:"required"`
|
||||
basePort *uint16 `nil_checker:"required"`
|
||||
path *string
|
||||
rawQuery *string
|
||||
useTLS *bool
|
||||
baseHost *string `nil_checker:"required"`
|
||||
basePort *uint16 `nil_checker:"required"`
|
||||
path *string
|
||||
rawQuery *string
|
||||
useTLS *bool
|
||||
channelSize *int64
|
||||
}
|
||||
|
||||
func NewSafeWebsocketClientBuilder() *SafeWebsocketClientBuilder {
|
||||
@@ -53,34 +102,43 @@ func (b *SafeWebsocketClientBuilder) RawQuery(rawQuery string) *SafeWebsocketCli
|
||||
return b
|
||||
}
|
||||
|
||||
func (b *SafeWebsocketClientBuilder) Build() (*SafeWebsocketClient, error) {
|
||||
func (b *SafeWebsocketClientBuilder) ChannelSize(channelSize int64) *SafeWebsocketClientBuilder {
|
||||
b.channelSize = &channelSize
|
||||
return b
|
||||
}
|
||||
|
||||
func (b *SafeWebsocketClientBuilder) Build(ctx context.Context) (*SafeWebsocketClient, error) {
|
||||
if err := internal.NilChecker(b); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
|
||||
var useTLS bool
|
||||
if b.useTLS != nil {
|
||||
useTLS = *b.useTLS
|
||||
}
|
||||
|
||||
if b.channelSize == nil {
|
||||
channelSize := int64(1)
|
||||
b.channelSize = &channelSize
|
||||
}
|
||||
|
||||
wsClient := SafeWebsocketClient{
|
||||
baseHost: *b.baseHost,
|
||||
basePort: *b.basePort,
|
||||
useTLS: useTLS,
|
||||
path: b.path,
|
||||
rawQuery: b.rawQuery,
|
||||
dataChannel: make(chan []byte, *b.channelSize),
|
||||
mu: custom_rwmutex.NewCustomRwMutex(),
|
||||
ctx: ctx,
|
||||
cancel: cancel,
|
||||
dataChannel: make(chan []byte, 1),
|
||||
mu: internal.NewCustomRwMutex(),
|
||||
reconnectCh: make(chan struct{}, 1),
|
||||
isConnected: false,
|
||||
doneMap: NewSafeMap[string, chan struct{}](),
|
||||
}
|
||||
|
||||
go wsClient.reconnectHandler()
|
||||
|
||||
if err := wsClient.connect(); err != nil {
|
||||
cancel()
|
||||
return nil, fmt.Errorf("failed to establish initial connection: %v", err)
|
||||
}
|
||||
|
||||
@@ -94,12 +152,14 @@ type SafeWebsocketClient struct {
|
||||
path *string
|
||||
rawQuery *string
|
||||
dataChannel chan []byte
|
||||
mu *internal.CustomRwMutex
|
||||
mu *custom_rwmutex.CustomRwMutex
|
||||
conn *websocket.Conn
|
||||
cancelFuncs []context.CancelFunc
|
||||
ctx context.Context
|
||||
cancel context.CancelFunc
|
||||
reconnectCh chan struct{}
|
||||
isConnected bool
|
||||
|
||||
doneMap *SafeMap[string, chan struct{}]
|
||||
}
|
||||
|
||||
func (wsClient *SafeWebsocketClient) connect() error {
|
||||
@@ -141,60 +201,80 @@ func (wsClient *SafeWebsocketClient) connect() error {
|
||||
})
|
||||
|
||||
wsClient.mu.WriteHandler(func() error {
|
||||
if wsClient.conn != nil {
|
||||
wsClient.conn.Close()
|
||||
}
|
||||
|
||||
wsClient.conn = conn
|
||||
|
||||
wsClient.isConnected = true
|
||||
|
||||
pingCtx, pingCancel := context.WithCancel(context.Background())
|
||||
go wsClient.startPingTicker(pingCtx)
|
||||
wsClient.cancelFuncs = append(wsClient.cancelFuncs, pingCancel)
|
||||
|
||||
receiverCtx, receiverCancel := context.WithCancel(context.Background())
|
||||
go wsClient.startReceiveHandler(receiverCtx)
|
||||
wsClient.cancelFuncs = append(wsClient.cancelFuncs, receiverCancel)
|
||||
|
||||
return nil
|
||||
})
|
||||
|
||||
go wsClient.startPingTicker()
|
||||
go wsClient.startReceiveHandler()
|
||||
go wsClient.reconnectHandler()
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (wsClient *SafeWebsocketClient) startPingTicker() {
|
||||
func (wsClient *SafeWebsocketClient) startPingTicker(ctx context.Context) {
|
||||
ticker := time.NewTicker(pingPeriod)
|
||||
defer ticker.Stop()
|
||||
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
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
|
||||
})
|
||||
case <-wsClient.ctx.Done():
|
||||
log.Println("Ping ticker stopped")
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (wsClient *SafeWebsocketClient) startReceiveHandler() {
|
||||
func (wsClient *SafeWebsocketClient) startReceiveHandler(ctx context.Context) {
|
||||
for {
|
||||
select {
|
||||
case <-wsClient.reconnectCh:
|
||||
case <-wsClient.ctx.Done():
|
||||
log.Println("Reconnect handler stopped")
|
||||
case <-ctx.Done():
|
||||
log.Println("receive handler stopped")
|
||||
return
|
||||
default:
|
||||
if err := wsClient.mu.WriteHandler(func() error {
|
||||
if err := wsClient.mu.ReadHandler(func() error {
|
||||
conn := wsClient.conn
|
||||
|
||||
if conn == nil {
|
||||
return fmt.Errorf("no active connection, waiting for reconnect")
|
||||
wsClient.triggerReconnect()
|
||||
return fmt.Errorf("connection closed")
|
||||
}
|
||||
_, message, err := conn.ReadMessage()
|
||||
if err != nil {
|
||||
return err
|
||||
wsClient.triggerReconnect()
|
||||
return fmt.Errorf("failed to read message: %v", err)
|
||||
}
|
||||
select {
|
||||
case wsClient.dataChannel <- message:
|
||||
case <-ctx.Done():
|
||||
log.Println("Reconnect handler stopped")
|
||||
return nil
|
||||
default:
|
||||
log.Println("Data channel full, dropping message")
|
||||
}
|
||||
wsClient.dataChannel <- message
|
||||
return nil
|
||||
}); err != nil {
|
||||
wsClient.triggerReconnect()
|
||||
return
|
||||
}
|
||||
}
|
||||
@@ -209,11 +289,74 @@ func (wsClient *SafeWebsocketClient) triggerReconnect() {
|
||||
}
|
||||
|
||||
func (wsClient *SafeWebsocketClient) reconnectHandler() {
|
||||
for range wsClient.reconnectCh {
|
||||
wsClient.connect()
|
||||
backoff := 1 * time.Second
|
||||
maxBackoff := 30 * time.Second
|
||||
for {
|
||||
select {
|
||||
case <-wsClient.reconnectCh:
|
||||
log.Println("Reconnect triggered")
|
||||
if wsClient.cancelFuncs != nil {
|
||||
for _, cancel := range wsClient.cancelFuncs {
|
||||
cancel()
|
||||
}
|
||||
}
|
||||
wsClient.isConnected = false
|
||||
|
||||
time.Sleep(100 * time.Millisecond)
|
||||
|
||||
isInnerLoop := true
|
||||
for isInnerLoop {
|
||||
log.Printf("Attempting reconnect in %v...", backoff)
|
||||
select {
|
||||
case <-time.After(backoff):
|
||||
if err := wsClient.connect(); err != nil {
|
||||
log.Printf("Reconnect failed: %v", err)
|
||||
if backoff < maxBackoff {
|
||||
backoff *= 2
|
||||
}
|
||||
continue
|
||||
}
|
||||
log.Println("Reconnected successfully")
|
||||
backoff = 1 * time.Second
|
||||
isInnerLoop = false
|
||||
continue
|
||||
case <-wsClient.ctx.Done():
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
case <-wsClient.ctx.Done():
|
||||
log.Println("reconnect handler stopped due to client shutdown")
|
||||
wsClient.Close()
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
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) Close() error {
|
||||
wsClient.mu.WriteHandler(func() error {
|
||||
if wsClient.cancelFuncs != nil {
|
||||
for _, cancel := range wsClient.cancelFuncs {
|
||||
cancel()
|
||||
}
|
||||
}
|
||||
if wsClient.conn != nil {
|
||||
wsClient.conn.Close()
|
||||
}
|
||||
wsClient.isConnected = false
|
||||
return nil
|
||||
})
|
||||
close(wsClient.dataChannel)
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -1,22 +1,39 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"log"
|
||||
"os"
|
||||
"os/signal"
|
||||
"syscall"
|
||||
|
||||
"git.neurocipta.com/rogerferdinan/safe-web-socket/v1/client"
|
||||
)
|
||||
|
||||
func main() {
|
||||
sigChan := make(chan os.Signal, 1)
|
||||
signal.Notify(sigChan, syscall.SIGINT, syscall.SIGTERM)
|
||||
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
|
||||
go func() {
|
||||
<-sigChan
|
||||
fmt.Println("\nReceived interrupt signal. Shutting down gracefully...")
|
||||
cancel()
|
||||
}()
|
||||
|
||||
wsClient, err := client.NewSafeWebsocketClientBuilder().
|
||||
BaseHost("localhost").
|
||||
BasePort(8080).
|
||||
Path("/ws/test/data_1").
|
||||
UseTLS(false).
|
||||
Build()
|
||||
Build(ctx)
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
|
||||
dataChannel := wsClient.DataChannel()
|
||||
|
||||
for data := range dataChannel {
|
||||
|
||||
Reference in New Issue
Block a user