-
Notifications
You must be signed in to change notification settings - Fork 3
/
client.go
188 lines (151 loc) · 4.2 KB
/
client.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
package qsse
import (
"bufio"
"context"
"crypto/tls"
"encoding/json"
"time"
quic "github.com/quic-go/quic-go"
"github.com/snapp-incubator/qsse/internal"
"go.uber.org/zap"
)
const (
reconnectRetryNumber = 5
reconnectRetryInterval = 5000
)
type Client interface {
SetEventHandler(topic string, handler func([]byte))
SetErrorHandler(handler func(code int, data map[string]any))
SetMessageHandler(handler func(topic string, event []byte))
}
type ClientConfig struct {
Token string
TLSConfig *tls.Config
ReconnectPolicy *ReconnectPolicy
}
type ReconnectPolicy struct {
Retry bool
RetryTimes int
RetryInterval int // duration between retry intervals in milliseconds
}
//nolint:funlen
func NewClient(address string, topics []string, config *ClientConfig) (Client, error) {
processedConfig := processConfig(config)
l := internal.NewLogger().Named("client")
connection, err := quic.DialAddr(context.Background(), address, processedConfig.TLSConfig, nil)
if err != nil {
if processedConfig.ReconnectPolicy.Retry {
l.Warn("Failed to connect to server, retrying...")
c, res := reconnect(
*processedConfig.ReconnectPolicy,
address,
processedConfig.TLSConfig,
l.Named("reconnect"),
)
if !res {
l.Warn("reconnecting failed")
return nil, err
}
connection = c
} else {
return nil, err //nolint:wrapcheck
}
}
client := internal.Client{
Connection: connection,
Token: processedConfig.Token,
Topics: topics,
Finder: internal.Finder{
Logger: l.Named("finder"),
},
OnEvent: make(map[string]func([]byte)),
OnMessage: internal.DefaultOnMessage,
OnError: internal.DefaultOnError,
Logger: l.Named("client"),
}
offer := internal.NewOffer(processedConfig.Token, topics)
bytes, err := json.Marshal(offer)
if err != nil {
l.Error("failed to marshal offer", zap.Error(err))
return nil, internal.ErrFailedToMarshal
}
stream, err := connection.OpenUniStream()
if err != nil {
l.Error("failed to open send stream", zap.Error(err))
err = internal.CloseClientConnection(
connection,
internal.CodeFailedToCreateStream,
internal.ErrFailedToCreateStream,
)
if err != nil {
l.Error("failed to close client connection", zap.Error(err))
}
return nil, internal.ErrFailedToCreateStream
}
err = internal.WriteData(bytes, stream)
if err != nil {
l.Error("failed to send offer to server", zap.Error(err))
err = internal.CloseClientConnection(
connection,
internal.CodeFailedToSendOffer,
internal.ErrFailedToSendOffer,
)
if err != nil {
l.Error("failed to close client connection", zap.Error(err))
}
return nil, internal.ErrFailedToSendOffer
}
_ = stream.Close()
receiveStream, err := connection.AcceptUniStream(context.Background())
if err != nil {
l.Error("failed to open receive stream", zap.Error(err))
err = internal.CloseClientConnection(
connection,
internal.CodeFailedToCreateStream,
internal.ErrFailedToCreateStream,
)
if err != nil {
l.Error("failed to close client connection", zap.Error(err))
}
return nil, internal.ErrFailedToCreateStream
}
reader := bufio.NewReader(receiveStream)
go client.AcceptEvents(reader)
return &client, nil
}
func processConfig(config *ClientConfig) ClientConfig {
if config == nil {
return ClientConfig{
Token: "",
TLSConfig: GetSimpleTLS(),
ReconnectPolicy: &ReconnectPolicy{
Retry: false,
RetryTimes: reconnectRetryNumber,
RetryInterval: reconnectRetryInterval,
},
}
}
if config.TLSConfig == nil {
config.TLSConfig = GetSimpleTLS()
}
if config.ReconnectPolicy == nil {
config.ReconnectPolicy = &ReconnectPolicy{
Retry: false,
RetryTimes: reconnectRetryNumber,
RetryInterval: reconnectRetryInterval,
}
}
return *config
}
//nolint:typecheck
func reconnect(policy ReconnectPolicy, address string, tlcCfg *tls.Config, l *zap.Logger) (quic.Connection, bool) {
for range policy.RetryTimes {
connection, err := quic.DialAddr(context.Background(), address, tlcCfg, nil)
if err == nil {
return connection, true
}
l.Error("failed to reconnect", zap.Error(err))
time.Sleep(time.Duration(policy.RetryInterval) * time.Millisecond)
}
return nil, false
}