Compare commits
3 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 752804cc58 | |||
| e686e69a24 | |||
| 034e5b68e0 |
@@ -6,6 +6,7 @@ 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"
|
||||||
@@ -17,6 +18,52 @@ const (
|
|||||||
pingPeriod = 10 * time.Second
|
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 {
|
type SafeWebsocketClientBuilder struct {
|
||||||
baseHost *string `nil_checker:"required"`
|
baseHost *string `nil_checker:"required"`
|
||||||
basePort *uint16 `nil_checker:"required"`
|
basePort *uint16 `nil_checker:"required"`
|
||||||
@@ -74,8 +121,11 @@ func (b *SafeWebsocketClientBuilder) Build() (*SafeWebsocketClient, error) {
|
|||||||
mu: custom_rwmutex.NewCustomRwMutex(),
|
mu: custom_rwmutex.NewCustomRwMutex(),
|
||||||
reconnectCh: make(chan struct{}, 1),
|
reconnectCh: make(chan struct{}, 1),
|
||||||
isConnected: false,
|
isConnected: false,
|
||||||
|
doneMap: NewSafeMap[string, chan struct{}](),
|
||||||
}
|
}
|
||||||
|
|
||||||
|
go wsClient.reconnectHandler()
|
||||||
|
|
||||||
if err := wsClient.connect(); err != nil {
|
if err := wsClient.connect(); err != nil {
|
||||||
return nil, fmt.Errorf("failed to establish initial connection: %v", err)
|
return nil, fmt.Errorf("failed to establish initial connection: %v", err)
|
||||||
}
|
}
|
||||||
@@ -96,6 +146,8 @@ type SafeWebsocketClient struct {
|
|||||||
cancel context.CancelFunc
|
cancel context.CancelFunc
|
||||||
reconnectCh chan struct{}
|
reconnectCh chan struct{}
|
||||||
isConnected bool
|
isConnected bool
|
||||||
|
|
||||||
|
doneMap *SafeMap[string, chan struct{}]
|
||||||
}
|
}
|
||||||
|
|
||||||
func (wsClient *SafeWebsocketClient) connect() error {
|
func (wsClient *SafeWebsocketClient) connect() error {
|
||||||
@@ -139,69 +191,75 @@ func (wsClient *SafeWebsocketClient) connect() error {
|
|||||||
})
|
})
|
||||||
|
|
||||||
wsClient.mu.WriteHandler(func() error {
|
wsClient.mu.WriteHandler(func() error {
|
||||||
|
if wsClient.conn != nil {
|
||||||
|
wsClient.conn.Close()
|
||||||
|
}
|
||||||
|
|
||||||
ctx, cancel := context.WithCancel(context.Background())
|
ctx, cancel := context.WithCancel(context.Background())
|
||||||
wsClient.ctx = ctx
|
wsClient.ctx = ctx
|
||||||
wsClient.cancel = cancel
|
wsClient.cancel = cancel
|
||||||
wsClient.conn = conn
|
wsClient.conn = conn
|
||||||
wsClient.isConnected = true
|
wsClient.isConnected = true
|
||||||
|
|
||||||
|
go wsClient.startPingTicker(ctx)
|
||||||
|
go wsClient.startReceiveHandler(ctx)
|
||||||
|
|
||||||
return nil
|
return nil
|
||||||
})
|
})
|
||||||
|
|
||||||
go wsClient.startPingTicker()
|
|
||||||
go wsClient.startReceiveHandler()
|
|
||||||
go wsClient.reconnectHandler()
|
|
||||||
|
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (wsClient *SafeWebsocketClient) startPingTicker() {
|
func (wsClient *SafeWebsocketClient) startPingTicker(ctx context.Context) {
|
||||||
ticker := time.NewTicker(pingPeriod)
|
ticker := time.NewTicker(pingPeriod)
|
||||||
defer ticker.Stop()
|
defer ticker.Stop()
|
||||||
|
|
||||||
for {
|
for {
|
||||||
select {
|
select {
|
||||||
case <-ticker.C:
|
case <-ticker.C:
|
||||||
wsClient.mu.WriteHandler(func() error {
|
wsClient.mu.WriteHandler(func() error {
|
||||||
|
if wsClient.conn == nil {
|
||||||
|
return fmt.Errorf("connecrtion closed")
|
||||||
|
}
|
||||||
if err := wsClient.conn.WriteMessage(websocket.PingMessage, []byte{}); err != nil {
|
if err := wsClient.conn.WriteMessage(websocket.PingMessage, []byte{}); err != nil {
|
||||||
log.Printf("Ping failed: %v. Will attempt reconnect.", err)
|
log.Printf("Ping failed: %v. Will attempt reconnect.", err)
|
||||||
wsClient.triggerReconnect()
|
wsClient.triggerReconnect()
|
||||||
}
|
}
|
||||||
return nil
|
return nil
|
||||||
})
|
})
|
||||||
case <-wsClient.ctx.Done():
|
case <-ctx.Done():
|
||||||
log.Println("Ping ticker stopped")
|
log.Println("Ping ticker stopped due to context cancellation")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (wsClient *SafeWebsocketClient) startReceiveHandler() {
|
func (wsClient *SafeWebsocketClient) startReceiveHandler(ctx context.Context) {
|
||||||
for {
|
for {
|
||||||
select {
|
select {
|
||||||
case <-wsClient.ctx.Done():
|
case <-ctx.Done():
|
||||||
log.Println("Reconnect handler stopped")
|
log.Println("Reconnect handler stopped")
|
||||||
return
|
return
|
||||||
default:
|
default:
|
||||||
// if err := wsClient.mu.ReadHandler(func() error {
|
wsClient.mu.ReadHandler(func() error {
|
||||||
conn := wsClient.conn
|
conn := wsClient.conn
|
||||||
|
|
||||||
if conn == nil {
|
if conn == nil {
|
||||||
wsClient.triggerReconnect()
|
wsClient.triggerReconnect()
|
||||||
return
|
return fmt.Errorf("connection closed")
|
||||||
// return fmt.Errorf("no active connection, waiting for reconnect")
|
|
||||||
}
|
}
|
||||||
_, message, err := conn.ReadMessage()
|
_, message, err := conn.ReadMessage()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
wsClient.triggerReconnect()
|
wsClient.triggerReconnect()
|
||||||
return
|
return fmt.Errorf("failed to read message: %v", err)
|
||||||
// return err
|
|
||||||
}
|
}
|
||||||
wsClient.dataChannel <- message
|
select {
|
||||||
// return nil
|
case wsClient.dataChannel <- message:
|
||||||
// }); err != nil {
|
default:
|
||||||
// wsClient.triggerReconnect()
|
log.Println("Data channel full, dropping message")
|
||||||
// return
|
}
|
||||||
// }
|
return nil
|
||||||
|
})
|
||||||
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -214,12 +272,40 @@ func (wsClient *SafeWebsocketClient) triggerReconnect() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (wsClient *SafeWebsocketClient) reconnectHandler() {
|
func (wsClient *SafeWebsocketClient) reconnectHandler() {
|
||||||
|
backoff := 1 * time.Second
|
||||||
|
maxBackoff := 30 * time.Second
|
||||||
for {
|
for {
|
||||||
select {
|
select {
|
||||||
case <-wsClient.reconnectCh:
|
case <-wsClient.reconnectCh:
|
||||||
|
log.Println("Reconnect triggered")
|
||||||
|
wsClient.mu.WriteHandler(func() error {
|
||||||
|
if wsClient.cancel != nil {
|
||||||
wsClient.cancel()
|
wsClient.cancel()
|
||||||
wsClient.connect()
|
}
|
||||||
|
wsClient.isConnected = false
|
||||||
|
return nil
|
||||||
|
})
|
||||||
|
|
||||||
|
time.Sleep(100 * time.Millisecond)
|
||||||
|
|
||||||
|
for {
|
||||||
|
log.Println("Attempting reconnect in %v...", backoff)
|
||||||
|
select {
|
||||||
|
case <-time.After(backoff):
|
||||||
|
if err := wsClient.connect(); err != nil {
|
||||||
|
log.Println("Reconnect failed: %v", err)
|
||||||
|
if backoff < maxBackoff {
|
||||||
|
backoff *= 2
|
||||||
|
}
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
log.Println("Reconnected successfully")
|
||||||
|
backoff = 1 * time.Second
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
case <-wsClient.ctx.Done():
|
case <-wsClient.ctx.Done():
|
||||||
|
log.Println("Reconnect handler stopped due to client shutdown")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user