-
Notifications
You must be signed in to change notification settings - Fork 1
/
test_convergence.go
327 lines (301 loc) · 8.89 KB
/
test_convergence.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
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
package e2e
import (
"bytes"
"fmt"
"io"
"net/url"
"strings"
"sync"
"time"
"github.com/google/go-cmp/cmp"
"github.com/google/go-cmp/cmp/cmpopts"
"github.com/pkg/errors"
messagev1 "github.com/xmtp/proto/v3/go/message_api/v1"
apiclient "github.com/xmtp/xmtpd/pkg/api/client"
"github.com/xmtp/xmtpd/pkg/context"
"github.com/xmtp/xmtpd/pkg/zap"
"google.golang.org/protobuf/proto"
)
func (e *E2E) testConvergence(name string) error {
nodeHosts := make([]string, len(e.opts.APIURLs))
for i, apiURL := range e.opts.APIURLs {
url, err := url.Parse(apiURL)
if err != nil {
return err
}
nodeHosts[i] = url.Hostname()
}
// Initialize clients for each node.
clients := make([]apiclient.Client, len(e.opts.APIURLs))
for i, apiURL := range e.opts.APIURLs {
appVersion := "xmtpd-e2e/"
if len(e.opts.GitCommit) > 0 {
appVersion += e.opts.GitCommit[:7]
}
apiURL, clientOpts, err := parseAPIURL(apiURL)
if err != nil {
return err
}
clients[i] = apiclient.NewHTTPClient(e.log, apiURL, e.opts.GitCommit, appVersion, clientOpts...)
defer clients[i].Close()
}
topic := "test-" + e.randomStringLower(12)
ctx := context.WithTimeout(e.ctx, 30*time.Second)
defer ctx.Close()
failedNodes := make([]bool, len(clients))
// Subscribe across nodes.
subscribeStart := time.Now().UTC()
subs := make([]apiclient.Stream, len(clients))
for nodeIndex, client := range clients {
sub, err := client.Subscribe(ctx, &messagev1.SubscribeRequest{
ContentTopics: []string{
topic,
},
})
if err != nil {
if err == context.Canceled {
e.log.Debug("context canceled", zap.Error(err))
return nil
}
duration := time.Since(subscribeStart)
e.log.Error("error subscribing", zap.Error(err))
e.metrics.recordSubscribe(e.ctx, name, nodeHosts[nodeIndex], "failed", duration)
clients[nodeIndex] = nil
failedNodes[nodeIndex] = true
} else {
subs[nodeIndex] = sub
defer sub.Close()
duration := time.Since(subscribeStart)
e.metrics.recordSubscribe(e.ctx, name, nodeHosts[nodeIndex], "passed", duration)
}
}
// Publish messages.
publishStart := time.Now().UTC()
envs := []*messagev1.Envelope{}
var envsLock sync.Mutex
var publishGroup sync.WaitGroup
for nodeIndex, client := range clients {
if client == nil {
continue
}
client := client
nodeIndex := nodeIndex
publishGroup.Add(1)
go func() {
defer publishGroup.Done()
clientEnvs := make([]*messagev1.Envelope, e.opts.MessagePerClient)
for j := 0; j < e.opts.MessagePerClient; j++ {
clientEnvs[j] = &messagev1.Envelope{
ContentTopic: topic,
TimestampNs: uint64(j + 1),
Message: []byte(fmt.Sprintf("msg%d-%d", nodeIndex+1, j+1)),
}
}
func() {
envsLock.Lock()
defer envsLock.Unlock()
envs = append(envs, clientEnvs...)
}()
_, err := client.Publish(ctx, &messagev1.PublishRequest{
Envelopes: clientEnvs,
})
if err != nil {
duration := time.Since(publishStart)
e.log.Error("error publishing", zap.Error(err), zap.Duration("duration", time.Since(publishStart)))
e.metrics.recordPublish(e.ctx, name, nodeHosts[nodeIndex], "failed", duration)
failedNodes[nodeIndex] = true
return
}
duration := time.Since(publishStart)
e.log.Info("published", zap.Duration("duration", duration), zap.String("node", nodeHosts[nodeIndex]))
e.metrics.recordPublish(e.ctx, name, nodeHosts[nodeIndex], "passed", duration)
}()
}
publishGroup.Wait()
// Expect them to be relayed to each subscription.
var subscribeGroup sync.WaitGroup
for nodeIndex, sub := range subs {
if sub == nil {
continue
}
sub := sub
nodeIndex := nodeIndex
subscribeGroup.Add(1)
go func() {
defer subscribeGroup.Done()
envC := make(chan *messagev1.Envelope, 100)
go func(sub apiclient.Stream) {
for {
env, err := sub.Next(ctx)
if err != nil {
if isErrClosedConnection(err) || err == context.Canceled {
break
}
e.log.Error("getting next", zap.Error(err))
break
}
if env == nil {
continue
}
envC <- env
}
}(sub)
err := subscribeExpect(envC, envs)
if err != nil {
duration := time.Since(publishStart)
e.log.Error("error checking subscription", zap.Error(err), zap.Duration("duration", time.Since(publishStart)))
e.metrics.recordSubscribeConvergence(e.ctx, name, nodeHosts[nodeIndex], "failed", duration)
failedNodes[nodeIndex] = true
return
}
subscribeConvergenceDuration := time.Since(publishStart)
e.log.Info("subscribe converged", zap.Duration("duration", subscribeConvergenceDuration), zap.String("node", nodeHosts[nodeIndex]))
e.metrics.recordSubscribeConvergence(e.ctx, name, nodeHosts[nodeIndex], "passed", subscribeConvergenceDuration)
}()
}
// Expect that they're stored.
var queryGroup sync.WaitGroup
for nodeIndex, client := range clients {
if client == nil {
continue
}
client := client
nodeIndex := nodeIndex
queryGroup.Add(1)
go func() {
defer queryGroup.Done()
err := e.expectQueryMessagesEventually(ctx, client, []string{topic}, envs)
if err != nil {
duration := time.Since(publishStart)
e.log.Error("error querying", zap.Error(err), zap.Duration("duration", duration))
e.metrics.recordQueryConvergence(e.ctx, name, nodeHosts[nodeIndex], "failed", duration)
failedNodes[nodeIndex] = true
return
}
duration := time.Since(publishStart)
e.log.Info("query converged", zap.Duration("duration", duration), zap.String("node", nodeHosts[nodeIndex]))
e.metrics.recordQueryConvergence(e.ctx, name, nodeHosts[nodeIndex], "passed", duration)
}()
}
subscribeGroup.Wait()
queryGroup.Wait()
var failedCount int
for _, failed := range failedNodes {
if !failed {
continue
}
failedCount++
}
if failedCount > 0 {
return errors.New("some nodes were unavailable or failed to converge")
}
return nil
}
func subscribeExpect(envC chan *messagev1.Envelope, envs []*messagev1.Envelope) error {
receivedEnvs := []*messagev1.Envelope{}
waitC := time.After(5 * time.Second)
var done bool
for !done {
select {
case env := <-envC:
receivedEnvs = append(receivedEnvs, env)
if len(receivedEnvs) == len(envs) {
done = true
}
case <-waitC:
done = true
}
}
err := envsDiff(envs, receivedEnvs)
if err != nil {
return errors.Wrap(err, "expected subscribe envelopes")
}
return nil
}
func isErrClosedConnection(err error) bool {
return errors.Is(err, io.EOF) || strings.Contains(err.Error(), "closed network connection") || strings.Contains(err.Error(), "response body closed")
}
func (e *E2E) expectQueryMessagesEventually(ctx context.Context, client apiclient.Client, contentTopics []string, expectedEnvs []*messagev1.Envelope) error {
timeout := 10 * time.Second
started := time.Now()
for {
envs, err := query(ctx, client, contentTopics)
if err != nil {
return errors.Wrap(err, "querying")
}
if len(envs) == len(expectedEnvs) {
err := envsDiff(envs, expectedEnvs)
if err != nil {
return errors.Wrap(err, "expected query envelopes")
}
break
}
if time.Since(started) > timeout {
err := envsDiff(envs, expectedEnvs)
if err != nil {
return errors.Wrap(err, "expected query envelopes")
}
return fmt.Errorf("timeout waiting for query expectation with no diff")
}
time.Sleep(e.opts.QueryConvergenceDelay)
}
return nil
}
func query(ctx context.Context, client apiclient.Client, contentTopics []string) ([]*messagev1.Envelope, error) {
var envs []*messagev1.Envelope
var pagingInfo *messagev1.PagingInfo
for {
res, err := client.Query(ctx, &messagev1.QueryRequest{
ContentTopics: contentTopics,
PagingInfo: pagingInfo,
})
if err != nil {
return nil, err
}
envs = append(envs, res.Envelopes...)
if len(res.Envelopes) == 0 || res.PagingInfo == nil || res.PagingInfo.Cursor == nil {
break
}
pagingInfo = res.PagingInfo
}
return envs, nil
}
func envsDiff(a, b []*messagev1.Envelope) error {
diff := cmp.Diff(a, b,
cmpopts.SortSlices(func(a, b *messagev1.Envelope) bool {
if a.ContentTopic != b.ContentTopic {
return a.ContentTopic < b.ContentTopic
}
if a.TimestampNs != b.TimestampNs {
return a.TimestampNs < b.TimestampNs
}
return bytes.Compare(a.Message, b.Message) < 0
}),
cmp.Comparer(proto.Equal),
)
if diff != "" {
return fmt.Errorf("expected equal, diff: %s", diff)
}
return nil
}
func parseAPIURL(apiURL string) (string, []apiclient.Option, error) {
// If the API URL is a subdomain of localhost, then replace it with
// localhost and include a Host header, since Go doesn't resolve this
// DNS properly.
opts := []apiclient.Option{}
url, err := url.Parse(apiURL)
if err != nil {
return "", nil, err
}
urlParts := strings.Split(url.Hostname(), ".")
if len(urlParts) == 2 && urlParts[1] == "localhost" {
opts = append(opts, apiclient.WithHeader("Host", url.Hostname()))
url.Host = "localhost"
port := url.Port()
if port != "80" {
url.Host += ":" + port
}
apiURL = url.String()
}
return apiURL, opts, nil
}