This repository was archived by the owner on May 31, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathstream.go
188 lines (169 loc) · 4.75 KB
/
stream.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
// Copyright 2022 Blockdaemon Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package pyth
import (
"context"
"errors"
"net"
"sync"
"time"
"github.com/cenkalti/backoff/v4"
"github.com/gagliardetto/solana-go"
"github.com/gagliardetto/solana-go/rpc"
"github.com/gagliardetto/solana-go/rpc/ws"
"go.uber.org/zap"
)
// StreamPriceAccounts creates a new stream of price account updates.
//
// It will reconnect automatically if the WebSocket connection breaks or stalls.
func (c *Client) StreamPriceAccounts() *PriceAccountStream {
ctx, cancel := context.WithCancel(context.Background())
stream := &PriceAccountStream{
cancel: cancel,
updates: make(chan PriceAccountEntry),
client: c,
}
stream.errLock.Lock()
go stream.runWrapper(ctx)
return stream
}
// PriceAccountStream is an ongoing stream of on-chain price account updates.
type PriceAccountStream struct {
cancel context.CancelFunc
updates chan PriceAccountEntry
client *Client
err error
errLock sync.Mutex
}
// Updates returns a channel with new price account updates.
func (p *PriceAccountStream) Updates() <-chan PriceAccountEntry {
return p.updates
}
// Err returns the reason why the price account stream is closed.
// Will block until the stream has actually closed.
// Returns nil if closure was expected.
func (p *PriceAccountStream) Err() error {
p.errLock.Lock()
defer p.errLock.Unlock()
return p.err
}
// Close must be called when no more updates are needed.
func (p *PriceAccountStream) Close() {
p.cancel()
}
func (p *PriceAccountStream) runWrapper(ctx context.Context) {
defer p.errLock.Unlock()
p.err = p.run(ctx)
}
func (p *PriceAccountStream) run(ctx context.Context) error {
defer close(p.updates)
const retryInterval = 3 * time.Second
return backoff.Retry(func() error {
err := p.runConn(ctx)
switch {
case errors.Is(err, context.Canceled), errors.Is(err, context.DeadlineExceeded):
return backoff.Permanent(err)
default:
p.client.Log.Error("Stream failed, restarting", zap.Error(err))
return err
}
}, backoff.WithContext(backoff.NewConstantBackOff(retryInterval), ctx))
}
func (p *PriceAccountStream) runConn(ctx context.Context) error {
client, err := ws.Connect(ctx, p.client.WebSocketURL)
if err != nil {
return err
}
defer client.Close()
// Make sure client cannot outlive context.
go func() {
defer client.Close()
<-ctx.Done()
}()
metricsWsActiveConns.Inc()
defer metricsWsActiveConns.Dec()
sub, err := client.ProgramSubscribeWithOpts(
p.client.Env.Program,
rpc.CommitmentProcessed,
solana.EncodingBase64Zstd,
[]rpc.RPCFilter{
{
Memcmp: &rpc.RPCFilterMemcmp{
Offset: 0,
Bytes: solana.Base58{
0xd4, 0xc3, 0xb2, 0xa1, // Magic
0x02, 0x00, 0x00, 0x00, // V2
},
},
},
},
)
if err != nil {
return err
}
// Stream updates.
for {
if err := p.readNextUpdate(ctx, sub); err != nil {
return err
}
}
}
func (p *PriceAccountStream) readNextUpdate(ctx context.Context, sub *ws.ProgramSubscription) error {
// If no update comes in within 20 seconds, bail.
const readTimeout = 20 * time.Second
ctx, cancel := context.WithTimeout(ctx, readTimeout)
defer cancel()
go func() {
<-ctx.Done()
// Terminate subscription if above timer has expired.
if errors.Is(ctx.Err(), context.DeadlineExceeded) {
p.client.Log.Warn("Read deadline exceeded, terminating WebSocket connection",
zap.Duration("timeout", readTimeout))
sub.Unsubscribe()
}
}()
// Read next account update from WebSockets.
update, err := sub.Recv()
if err != nil {
return err
} else if update == nil {
return net.ErrClosed
}
metricsWsEventsTotal.Inc()
// Decode update.
if update.Value.Account == nil || update.Value.Account.Owner != p.client.Env.Program {
return nil
}
accountData := update.Value.Account.Data.GetBinary()
if PeekAccount(accountData) != AccountTypePrice {
return nil
}
priceAcc := new(PriceAccount)
if err := priceAcc.UnmarshalBinary(accountData); err != nil {
p.client.Log.Warn("Failed to unmarshal priceAcc account", zap.Error(err))
return nil
}
// Send update to channel.
msg := PriceAccountEntry{
Slot: update.Context.Slot,
Pubkey: update.Value.Pubkey,
PriceAccount: priceAcc,
}
select {
case <-ctx.Done():
return ctx.Err()
case p.updates <- msg:
return nil
}
}