-
Notifications
You must be signed in to change notification settings - Fork 338
/
streamtest.go
438 lines (358 loc) · 9.58 KB
/
streamtest.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
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
// Copyright 2020 The Swarm Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package streamtest
import (
"context"
"errors"
"io"
"sync"
"testing"
"time"
"github.com/ethersphere/bee/pkg/p2p"
"github.com/ethersphere/bee/pkg/swarm"
ma "github.com/multiformats/go-multiaddr"
)
var (
ErrRecordsNotFound = errors.New("records not found")
ErrStreamNotSupported = errors.New("stream not supported")
ErrStreamClosed = errors.New("stream closed")
ErrStreamFullcloseTimeout = errors.New("fullclose timeout")
fullCloseTimeout = fullCloseTimeoutDefault // timeout of fullclose
fullCloseTimeoutDefault = 5 * time.Second // default timeout used for helper function to reset timeout when changed
noopMiddleware = func(f p2p.HandlerFunc) p2p.HandlerFunc {
return f
}
)
type Recorder struct {
base swarm.Address
fullNode bool
records map[string][]*Record
recordsMu sync.Mutex
protocols []p2p.ProtocolSpec
middlewares []p2p.HandlerMiddleware
streamErr func(swarm.Address, string, string, string) error
pingErr func(ma.Multiaddr) (time.Duration, error)
protocolsWithPeers map[string]p2p.ProtocolSpec
}
func WithProtocols(protocols ...p2p.ProtocolSpec) Option {
return optionFunc(func(r *Recorder) {
r.protocols = append(r.protocols, protocols...)
})
}
func WithPeerProtocols(protocolsWithPeers map[string]p2p.ProtocolSpec) Option {
return optionFunc(func(r *Recorder) {
r.protocolsWithPeers = protocolsWithPeers
})
}
func WithMiddlewares(middlewares ...p2p.HandlerMiddleware) Option {
return optionFunc(func(r *Recorder) {
r.middlewares = append(r.middlewares, middlewares...)
})
}
func WithBaseAddr(a swarm.Address) Option {
return optionFunc(func(r *Recorder) {
r.base = a
})
}
func WithLightNode() Option {
return optionFunc(func(r *Recorder) {
r.fullNode = false
})
}
func WithStreamError(streamErr func(swarm.Address, string, string, string) error) Option {
return optionFunc(func(r *Recorder) {
r.streamErr = streamErr
})
}
func WithPingErr(pingErr func(ma.Multiaddr) (time.Duration, error)) Option {
return optionFunc(func(r *Recorder) {
r.pingErr = pingErr
})
}
func New(opts ...Option) *Recorder {
r := &Recorder{
records: make(map[string][]*Record),
fullNode: true,
}
r.middlewares = append(r.middlewares, noopMiddleware)
for _, o := range opts {
o.apply(r)
}
return r
}
func (r *Recorder) SetProtocols(protocols ...p2p.ProtocolSpec) {
r.protocols = append(r.protocols, protocols...)
}
func (r *Recorder) NewStream(ctx context.Context, addr swarm.Address, h p2p.Headers, protocolName, protocolVersion, streamName string) (p2p.Stream, error) {
if r.streamErr != nil {
err := r.streamErr(addr, protocolName, protocolVersion, streamName)
if err != nil {
return nil, err
}
}
recordIn := newRecord()
recordOut := newRecord()
streamOut := newStream(recordIn, recordOut)
streamIn := newStream(recordOut, recordIn)
var handler p2p.HandlerFunc
var headler p2p.HeadlerFunc
peerHandlers, ok := r.protocolsWithPeers[addr.String()]
if !ok {
for _, p := range r.protocols {
if p.Name == protocolName && p.Version == protocolVersion {
peerHandlers = p
}
}
}
for _, s := range peerHandlers.StreamSpecs {
if s.Name == streamName {
handler = s.Handler
headler = s.Headler
}
}
if handler == nil {
return nil, ErrStreamNotSupported
}
for i := len(r.middlewares) - 1; i >= 0; i-- {
handler = r.middlewares[i](handler)
}
if headler != nil {
streamOut.headers = headler(h, addr)
}
record := &Record{in: recordIn, out: recordOut, done: make(chan struct{})}
go func() {
defer close(record.done)
// pass a new context to handler,
streamIn.responseHeaders = streamOut.headers
// do not cancel it with the client stream context
err := handler(context.Background(), p2p.Peer{Address: r.base, FullNode: r.fullNode}, streamIn)
if err != nil && !errors.Is(err, io.EOF) {
record.setErr(err)
}
}()
id := addr.String() + p2p.NewSwarmStreamName(protocolName, protocolVersion, streamName)
r.recordsMu.Lock()
defer r.recordsMu.Unlock()
r.records[id] = append(r.records[id], record)
return streamOut, nil
}
func (r *Recorder) Ping(ctx context.Context, addr ma.Multiaddr) (rtt time.Duration, err error) {
if r.pingErr != nil {
return r.pingErr(addr)
}
return rtt, err
}
func (r *Recorder) Records(addr swarm.Address, protocolName, protocolVersio, streamName string) ([]*Record, error) {
id := addr.String() + p2p.NewSwarmStreamName(protocolName, protocolVersio, streamName)
r.recordsMu.Lock()
defer r.recordsMu.Unlock()
records, ok := r.records[id]
if !ok {
return nil, ErrRecordsNotFound
}
// wait for all records goroutines to terminate
for _, r := range records {
<-r.done
}
return records, nil
}
// WaitRecords waits for some time for records to come into the recorder. If msgs is 0, the timeoutSec period is waited to verify
// that _no_ messages arrive during this time period.
func (r *Recorder) WaitRecords(t *testing.T, addr swarm.Address, proto, version, stream string, msgs, timeoutSec int) []*Record {
t.Helper()
wait := 10 * time.Millisecond
iters := int((time.Duration(timeoutSec) * time.Second) / wait)
for i := 0; i < iters; i++ {
recs, _ := r.Records(addr, proto, version, stream)
if l := len(recs); l > msgs {
t.Fatalf("too many records. want %d got %d", msgs, l)
} else if msgs > 0 && l == msgs {
return recs
}
// we can be here if msgs == 0 && l == 0
// or msgs = x && l < x, both cases are fine
// and we should continue waiting
time.Sleep(wait)
}
if msgs > 0 {
t.Fatal("timed out while waiting for records")
}
return nil
}
type Record struct {
in *record
out *record
err error
errMu sync.Mutex
done chan struct{}
}
func (r *Record) In() []byte {
return r.in.bytes()
}
func (r *Record) Out() []byte {
return r.out.bytes()
}
func (r *Record) Err() error {
r.errMu.Lock()
defer r.errMu.Unlock()
return r.err
}
func (r *Record) setErr(err error) {
r.errMu.Lock()
defer r.errMu.Unlock()
r.err = err
}
type stream struct {
in *record
out *record
headers p2p.Headers
responseHeaders p2p.Headers
}
func newStream(in, out *record) *stream {
return &stream{in: in, out: out}
}
func (s *stream) Read(p []byte) (int, error) {
return s.out.Read(p)
}
func (s *stream) Write(p []byte) (int, error) {
return s.in.Write(p)
}
func (s *stream) Headers() p2p.Headers {
return s.headers
}
func (s *stream) ResponseHeaders() p2p.Headers {
return s.responseHeaders
}
func (s *stream) Close() error {
return s.in.Close()
}
func (s *stream) FullClose() error {
if err := s.Close(); err != nil {
_ = s.Reset()
return err
}
waitStart := time.Now()
for {
if s.out.Closed() {
return nil
}
if time.Since(waitStart) >= fullCloseTimeout {
return ErrStreamFullcloseTimeout
}
time.Sleep(10 * time.Millisecond)
}
}
func (s *stream) Reset() (err error) {
if err := s.in.Close(); err != nil {
_ = s.out.Close()
return err
}
return s.out.Close()
}
type record struct {
b []byte
c int
closed bool
closeMu sync.RWMutex
cond *sync.Cond
}
func newRecord() *record {
return &record{
cond: sync.NewCond(new(sync.Mutex)),
}
}
func (r *record) Read(p []byte) (n int, err error) {
r.cond.L.Lock()
defer r.cond.L.Unlock()
for r.c == len(r.b) && !r.Closed() {
r.cond.Wait()
}
end := r.c + len(p)
if end > len(r.b) {
end = len(r.b)
}
n = copy(p, r.b[r.c:end])
r.c += n
if r.Closed() {
err = io.EOF
}
return n, err
}
func (r *record) Write(p []byte) (int, error) {
r.cond.L.Lock()
defer r.cond.L.Unlock()
if r.Closed() {
return 0, ErrStreamClosed
}
defer r.cond.Signal()
r.b = append(r.b, p...)
return len(p), nil
}
func (r *record) Close() error {
r.cond.L.Lock()
defer r.cond.L.Unlock()
defer r.cond.Broadcast()
r.closeMu.Lock()
r.closed = true
r.closeMu.Unlock()
return nil
}
func (r *record) Closed() bool {
r.closeMu.RLock()
defer r.closeMu.RUnlock()
return r.closed
}
func (r *record) bytes() []byte {
r.cond.L.Lock()
defer r.cond.L.Unlock()
return r.b
}
type Option interface {
apply(*Recorder)
}
type optionFunc func(*Recorder)
func (f optionFunc) apply(r *Recorder) { f(r) }
var _ p2p.StreamerDisconnecter = (*RecorderDisconnecter)(nil)
type RecorderDisconnecter struct {
*Recorder
disconnected map[string]struct{}
blocklisted map[string]time.Duration
mu sync.RWMutex
}
func NewRecorderDisconnecter(r *Recorder) *RecorderDisconnecter {
return &RecorderDisconnecter{
Recorder: r,
disconnected: make(map[string]struct{}),
blocklisted: make(map[string]time.Duration),
}
}
func (r *RecorderDisconnecter) Disconnect(overlay swarm.Address, _ string) error {
r.mu.Lock()
defer r.mu.Unlock()
r.disconnected[overlay.String()] = struct{}{}
return nil
}
func (r *RecorderDisconnecter) Blocklist(overlay swarm.Address, d time.Duration, _ string) error {
r.mu.Lock()
defer r.mu.Unlock()
r.blocklisted[overlay.String()] = d
return nil
}
func (r *RecorderDisconnecter) IsDisconnected(overlay swarm.Address) bool {
r.mu.RLock()
defer r.mu.RUnlock()
_, yes := r.disconnected[overlay.String()]
return yes
}
func (r *RecorderDisconnecter) IsBlocklisted(overlay swarm.Address) (bool, time.Duration) {
r.mu.RLock()
defer r.mu.RUnlock()
d, yes := r.blocklisted[overlay.String()]
return yes, d
}
// NetworkStatus implements p2p.NetworkStatuser interface.
// It always returns p2p.NetworkStatusAvailable.
func (r *RecorderDisconnecter) NetworkStatus() p2p.NetworkStatus {
return p2p.NetworkStatusAvailable
}