-
Notifications
You must be signed in to change notification settings - Fork 1
/
node.go
296 lines (258 loc) · 7.37 KB
/
node.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
package testing
import (
"bytes"
"fmt"
"math/rand"
"os"
"sort"
"testing"
"time"
"github.com/stretchr/testify/require"
messagev1 "github.com/xmtp/proto/v3/go/message_api/v1"
"github.com/xmtp/xmtpd/pkg/api"
"github.com/xmtp/xmtpd/pkg/api/client"
"github.com/xmtp/xmtpd/pkg/context"
"github.com/xmtp/xmtpd/pkg/node"
memstore "github.com/xmtp/xmtpd/pkg/store/mem"
test "github.com/xmtp/xmtpd/pkg/testing"
"github.com/xmtp/xmtpd/pkg/zap"
)
type testNode struct {
*node.Node
name string
persistentPeers []string
store node.NodeStore
client client.Client
ctx context.Context
}
type TestNodeOption func(n *testNode)
func WithContext(ctx context.Context) TestNodeOption {
return func(n *testNode) {
n.ctx = ctx
}
}
func WithName(name string) TestNodeOption {
return func(n *testNode) {
n.name = name
}
}
func WithStore(store node.NodeStore) TestNodeOption {
return func(n *testNode) {
n.store = store
}
}
func WithPersistentPeers(addrs ...string) TestNodeOption {
return func(n *testNode) {
n.persistentPeers = addrs
}
}
func NewNode(t testing.TB, opts ...TestNodeOption) *testNode {
t.Helper()
tn := &testNode{}
for _, opt := range opts {
opt(tn)
}
if tn.ctx == nil {
tn.ctx = test.NewContext(t)
}
if tn.name != "" {
tn.ctx = context.WithLogger(tn.ctx, tn.ctx.Logger().Named(tn.name))
}
if tn.store == nil {
tn.store = memstore.NewNodeStore(tn.ctx)
}
var err error
tn.Node, err = node.New(tn.ctx, nil, tn.store, &node.Options{
P2P: node.P2POptions{
PersistentPeers: tn.persistentPeers,
},
})
require.NoError(t, err)
tn.client = client.NewHTTPClient(tn.ctx.Logger(), fmt.Sprintf("http://localhost:%d", tn.Node.APIHTTPListenPort()), "test", tn.name)
return tn
}
func (n *testNode) Close() error {
n.ctx.Close()
n.Node.Close()
return nil
}
func (n *testNode) Context() context.Context {
return n.ctx
}
func (n *testNode) Connect(t *testing.T, to *testNode) {
t.Helper()
err := n.Node.Connect(n.ctx, to.Address())
require.NoError(t, err)
}
func (n *testNode) Disconnect(t *testing.T, to *testNode) {
t.Helper()
err := n.Node.Disconnect(n.ctx, to.ID())
require.NoError(t, err)
}
func (n *testNode) WaitForPubSub(t *testing.T, to *testNode) {
t.Helper()
// Wait for peers to be connected and grafted to the pubsub topic.
// See https://github.com/libp2p/go-libp2p-pubsub/issues/331
log := n.ctx.Logger()
totalTimeout := 5 * time.Second
if os.Getenv("CI") == "true" {
totalTimeout = 10 * time.Second
}
retryTimeout := totalTimeout / 5
ticker := time.NewTicker(retryTimeout)
defer ticker.Stop()
attempt := 1
var connected bool
ctx := context.WithTimeout(n.ctx, totalTimeout)
defer ctx.Close()
topic := fmt.Sprintf("sync-%s-%s-%s", n.name, to.name, test.RandomStringLower(13))
syncLoop:
for {
select {
case <-ctx.Done():
log.Info("context closed", zap.Error(ctx.Err()))
break syncLoop
case <-ticker.C:
sentEnv := newRandomEnvelope(topic, attempt)
_, err := n.client.Publish(n.ctx, &messagev1.PublishRequest{
Envelopes: []*messagev1.Envelope{sentEnv},
})
require.NoError(t, err)
func() {
queryTicker := time.NewTicker(retryTimeout / 5)
defer queryTicker.Stop()
queryCtx := context.WithTimeout(ctx, retryTimeout)
defer queryCtx.Close()
checkLoop:
for {
select {
case <-queryCtx.Done():
return
case <-queryTicker.C:
res, err := to.client.Query(n.ctx, &messagev1.QueryRequest{
ContentTopics: []string{topic},
PagingInfo: &messagev1.PagingInfo{
Direction: messagev1.SortDirection_SORT_DIRECTION_DESCENDING,
Limit: 1,
},
})
if err != nil {
n.ctx.Logger().Debug("sync check err", zap.String("to", to.name), zap.Int("attempt", attempt), zap.Error(err))
continue checkLoop
}
if len(res.Envelopes) == 0 {
n.ctx.Logger().Debug("sync check none", zap.String("to", to.name), zap.Int("attempt", attempt))
continue checkLoop
}
if env := res.Envelopes[len(res.Envelopes)-1]; bytes.Equal(sentEnv.Message, env.Message) {
n.ctx.Logger().Debug("sync check", zap.String("to", to.name), zap.Int("attempt", attempt), zap.Int("got", int(env.TimestampNs)))
connected = true
return
}
}
}
}()
if connected {
break syncLoop
}
log.Debug("waiting for p2p connectivity sync message", zap.Int("attempt", attempt))
attempt++
}
}
require.True(t, connected, fmt.Sprintf("node %s failed to connect to node %s", n.name, to.name))
}
func (n *testNode) PublishRandom(t testing.TB, topic string, count int) []*messagev1.Envelope {
t.Helper()
envs := make([]*messagev1.Envelope, count)
for i := 0; i < count; i++ {
env := newRandomEnvelope(topic, rand.Intn(100))
res, err := n.client.Publish(n.ctx, &messagev1.PublishRequest{
Envelopes: []*messagev1.Envelope{env},
})
require.NoError(t, err)
require.NotNil(t, res)
envs[i] = env
}
return envs
}
func (n *testNode) Subscribe(t *testing.T, topic string) *testSubscriber {
sub := &testSubscriber{
Topic: topic,
}
stream, err := n.client.Subscribe(n.ctx, &messagev1.SubscribeRequest{
ContentTopics: []string{topic},
})
require.NoError(t, err)
sub.stream = stream
go func() {
for {
env, err := sub.stream.Next(n.ctx)
if err == context.Canceled {
return
}
require.NoError(t, err)
func() {
sub.Lock()
defer sub.Unlock()
sub.envs = append(sub.envs, env)
}()
}
}()
return sub
}
func (n *testNode) RequireQuery(t testing.TB, topic string, mods ...api.QueryModifier) []*messagev1.Envelope {
resp, err := n.Query(n.ctx, api.NewQuery(topic, mods...))
require.NoError(t, err)
return resp.Envelopes
}
func (n *testNode) RequireEventuallyStoredEvents(t *testing.T, topic string, expected []*messagev1.Envelope) {
t.Helper()
var res *messagev1.QueryResponse
require.Eventually(t, func() bool {
var err error
res, err = n.client.Query(n.ctx, &messagev1.QueryRequest{
ContentTopics: []string{topic},
})
require.NoError(t, err)
return len(res.Envelopes) == len(expected)
}, 3*time.Second, 100*time.Millisecond, "%s topic %s expected %d", n.name, topic, len(expected))
requireEnvelopesEqual(t, expected, res.Envelopes)
}
func requireEnvelopesEqual(t *testing.T, expected, actual []*messagev1.Envelope) {
t.Helper()
expected = append([]*messagev1.Envelope{}, expected...)
sort.Slice(expected, func(i, j int) bool {
d := int(expected[i].TimestampNs) - int(expected[j].TimestampNs)
if d != 0 {
return d < 0
}
return bytes.Compare(expected[i].Message, expected[j].Message) < 0
})
actual = append([]*messagev1.Envelope{}, actual...)
sort.Slice(actual, func(i, j int) bool {
d := int(actual[i].TimestampNs) - int(actual[j].TimestampNs)
if d != 0 {
return d < 0
}
return bytes.Compare(actual[i].Message, actual[j].Message) < 0
})
test.RequireProtoEqual(t, expected, actual)
}
func newRandomEnvelope(topic string, timestampNs int) *messagev1.Envelope {
return &messagev1.Envelope{
ContentTopic: topic,
TimestampNs: uint64(timestampNs),
Message: []byte("msg-" + test.RandomString(13)),
}
}
func RunTopicLifecycleTest(t *testing.T, s node.NodeStore) {
node := NewNode(t, WithStore(s))
node.PublishRandom(t, "t1", 10)
node.PublishRandom(t, "t2", 10)
node.PublishRandom(t, "t3", 10)
require.NoError(t, node.DeleteTopic("t2"))
topics, err := s.Topics()
require.NoError(t, err)
require.Equal(t, 2, len(topics))
require.NoError(t, node.Close())
}