-
Notifications
You must be signed in to change notification settings - Fork 19
/
candle_updates.go
236 lines (200 loc) · 6.62 KB
/
candle_updates.go
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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
// Copyright (c) 2022 Gobalsky Labs Limited
//
// Use of this software is governed by the Business Source License included
// in the LICENSE.DATANODE file and at https://www.mariadb.com/bsl11.
//
// Change Date: 18 months from the later of the date of the first publicly
// available Distribution of this version of the repository, and 25 June 2022.
//
// On the date above, in accordance with the Business Source License, use
// of this software will be governed by version 3 or later of the GNU General
// Public License.
package candlesv2
import (
"context"
"fmt"
"sync/atomic"
"time"
"code.vegaprotocol.io/vega/datanode/entities"
"code.vegaprotocol.io/vega/logging"
)
type candleSource interface {
GetCandleDataForTimeSpan(ctx context.Context, candleID string, from *time.Time, to *time.Time,
p entities.CursorPagination) ([]entities.Candle, entities.PageInfo, error)
}
type subscriptionMsg struct {
subscribe bool
id string
out chan entities.Candle
}
func (m subscriptionMsg) String() string {
if m.subscribe {
return fmt.Sprintf("unsubscribe, subscription id:%s", m.id)
}
return "subscribe"
}
type CandleUpdates struct {
log *logging.Logger
candleSource candleSource
candleID string
subscriptionMsgChan chan subscriptionMsg
nextSubscriptionID atomic.Uint64
config CandleUpdatesConfig
}
func NewCandleUpdates(ctx context.Context, log *logging.Logger, candleID string, candleSource candleSource,
config CandleUpdatesConfig,
) *CandleUpdates {
ces := &CandleUpdates{
log: log,
candleSource: candleSource,
candleID: candleID,
config: config,
subscriptionMsgChan: make(chan subscriptionMsg, config.CandleUpdatesStreamSubscriptionMsgBufferSize),
}
go ces.run(ctx)
return ces
}
func (s *CandleUpdates) run(ctx context.Context) {
subscriptions := map[string]chan entities.Candle{}
defer closeAllSubscriptions(subscriptions)
ticker := time.NewTicker(s.config.CandleUpdatesStreamInterval.Duration)
var lastCandle *entities.Candle
errorGettingCandleUpdates := false
for {
select {
case <-ctx.Done():
return
case subscriptionMsg := <-s.subscriptionMsgChan:
s.handleSubscription(subscriptions, subscriptionMsg, lastCandle)
default:
select {
case <-ctx.Done():
return
case subscription := <-s.subscriptionMsgChan:
s.handleSubscription(subscriptions, subscription, lastCandle)
case <-ticker.C:
if len(subscriptions) > 0 {
candles, err := s.getCandleUpdates(ctx, lastCandle)
if err != nil {
if !errorGettingCandleUpdates {
s.log.Errorf("failed to get candles for candle id", logging.String("candle", s.candleID), logging.Error(err))
}
errorGettingCandleUpdates = true
} else {
if errorGettingCandleUpdates {
s.log.Infof("successfully got candles for candle", logging.String("candle", s.candleID))
}
errorGettingCandleUpdates = false
if len(candles) > 0 {
lastCandle = &candles[len(candles)-1]
}
s.sendCandlesToSubscribers(candles, subscriptions)
}
} else {
lastCandle = nil
}
}
}
}
}
func (s *CandleUpdates) handleSubscription(subscriptions map[string]chan entities.Candle, subscription subscriptionMsg, lastCandle *entities.Candle) {
if subscription.subscribe {
s.addSubscription(subscriptions, subscription, lastCandle)
} else {
removeSubscription(subscriptions, subscription.id)
}
}
func (s *CandleUpdates) addSubscription(subscriptions map[string]chan entities.Candle, subscription subscriptionMsg, lastCandle *entities.Candle) {
subscriptions[subscription.id] = subscription.out
if lastCandle != nil {
s.sendCandlesToSubscribers([]entities.Candle{*lastCandle}, map[string]chan entities.Candle{subscription.id: subscription.out})
}
}
func removeSubscription(subscriptions map[string]chan entities.Candle, subscriptionID string) {
if _, ok := subscriptions[subscriptionID]; ok {
close(subscriptions[subscriptionID])
delete(subscriptions, subscriptionID)
}
}
func closeAllSubscriptions(subscribers map[string]chan entities.Candle) {
for _, subscriber := range subscribers {
close(subscriber)
}
}
// Subscribe returns a unique subscription id and channel on which updates will be sent.
func (s *CandleUpdates) Subscribe() (string, <-chan entities.Candle, error) {
out := make(chan entities.Candle, s.config.CandleUpdatesStreamBufferSize)
nextID := s.nextSubscriptionID.Add(1)
subscriptionID := fmt.Sprintf("%s-%d", s.candleID, nextID)
msg := subscriptionMsg{
subscribe: true,
id: subscriptionID,
out: out,
}
err := s.sendSubscriptionMessage(msg)
if err != nil {
return "", nil, err
}
return subscriptionID, out, nil
}
func (s *CandleUpdates) Unsubscribe(subscriptionID string) error {
msg := subscriptionMsg{
subscribe: false,
id: subscriptionID,
}
return s.sendSubscriptionMessage(msg)
}
func (s *CandleUpdates) sendSubscriptionMessage(msg subscriptionMsg) error {
if s.config.CandleUpdatesStreamSubscriptionMsgBufferSize == 0 {
s.subscriptionMsgChan <- msg
} else {
select {
case s.subscriptionMsgChan <- msg:
default:
return fmt.Errorf("failed to send subscription message \"%s\", subscription message buffer is full, try again later", msg)
}
}
return nil
}
func (s *CandleUpdates) getCandleUpdates(ctx context.Context, lastCandle *entities.Candle) ([]entities.Candle, error) {
ctx, cancelFn := context.WithTimeout(ctx, s.config.CandlesFetchTimeout.Duration)
defer cancelFn()
var updates []entities.Candle
var err error
if lastCandle != nil {
start := lastCandle.PeriodStart
var candles []entities.Candle
candles, _, err = s.candleSource.GetCandleDataForTimeSpan(ctx, s.candleID, &start, nil, entities.CursorPagination{})
if err != nil {
return nil, fmt.Errorf("getting candle updates:%w", err)
}
for _, candle := range candles {
if candle.LastUpdateInPeriod.After(lastCandle.LastUpdateInPeriod) {
updates = append(updates, candle)
}
}
} else {
last := int32(1)
pagination, err := entities.NewCursorPagination(nil, nil, &last, nil, false)
if err != nil {
return nil, err
}
updates, _, err = s.candleSource.GetCandleDataForTimeSpan(ctx, s.candleID, nil, nil, pagination)
if err != nil {
return nil, fmt.Errorf("getting candle updates:%w", err)
}
}
return updates, nil
}
func (s *CandleUpdates) sendCandlesToSubscribers(candles []entities.Candle, subscriptions map[string]chan entities.Candle) {
for subscriptionID, outCh := range subscriptions {
for _, candle := range candles {
select {
case outCh <- candle:
default:
removeSubscription(subscriptions, subscriptionID)
break
}
}
}
}