forked from sonirico/go-hyperliquid
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathws_uniq_subscriber.go
More file actions
86 lines (74 loc) · 1.74 KB
/
ws_uniq_subscriber.go
File metadata and controls
86 lines (74 loc) · 1.74 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
package hyperliquid
import (
"sync"
)
type callback func(any)
// uniqSubscriber is a subscriber that ensures only one active websocket subscription per unique key, keeping 1:N observers
// in sync with the latest data.
type uniqSubscriber struct {
mu sync.RWMutex
id string // trades:<coin>, ...
count int64
subscribers map[string]callback
subscriberFunc func(subscriptable)
unsubscriberFunc func(subscriptable)
subscriptionPayload subscriptable
}
func newUniqSubscriber(
id string,
payload subscriptable,
subscriberFunc, unsubscriberFunc func(subscriptable),
) *uniqSubscriber {
return &uniqSubscriber{
id: id,
subscriptionPayload: payload,
count: 0,
subscribers: make(map[string]callback),
subscriberFunc: subscriberFunc,
unsubscriberFunc: unsubscriberFunc,
}
}
func (u *uniqSubscriber) subscribe(id string, cb callback) {
u.mu.Lock()
if _, exists := u.subscribers[id]; exists {
u.mu.Unlock()
return
}
u.subscribers[id] = cb
u.count++
c := u.count
u.mu.Unlock()
if c == 1 {
u.subscriberFunc(u.subscriptionPayload)
}
}
func (u *uniqSubscriber) unsubscribe(id string) {
u.mu.Lock()
if _, exists := u.subscribers[id]; !exists {
u.mu.Unlock()
return
}
delete(u.subscribers, id)
c := u.count - 1
u.count = c
u.mu.Unlock()
if c == 0 {
u.unsubscriberFunc(u.subscriptionPayload)
}
}
func (u *uniqSubscriber) dispatch(data any) {
u.mu.RLock()
defer u.mu.RUnlock()
for _, cb := range u.subscribers {
cb(data)
}
}
func (u *uniqSubscriber) clear() {
u.mu.Lock()
defer u.mu.Unlock()
for id := range u.subscribers {
delete(u.subscribers, id)
}
u.count = 0
u.unsubscriberFunc(u.subscriptionPayload)
}