Debian Codegraph @

test/stress.go

raw symbols SCIP
1 package test
2
3 import (
4 "bytes"
5 "context"
6 "errors"
7 "fmt"
8 "io"
9 "sync"
10
11 "github.com/pion/transport/v2/connctx"
12 )
13
14 var errByteSequenceChanged = errors.New("byte sequence changed")
15
16 // Options represents the configuration of the stress test
17 type Options struct {
18 MsgSize int
19 MsgCount int
20 }
21
22 // Stress enables stress testing of a io.ReadWriter.
23 // It checks that packets are received correctly and in order.
24 func Stress(ca io.Writer, cb io.Reader, opt Options) error {
25 return StressContext(context.Background(), &wrappedWriter{ca}, &wrappedReader{cb}, opt)
26 }
27
28 // StressContext enables stress testing of a io.ReadWriter.
29 // It checks that packets are received correctly and in order.
30 func StressContext(ctx context.Context, ca connctx.Writer, cb connctx.Reader, opt Options) error {
31 bufs := make(chan []byte, opt.MsgCount)
32 errCh := make(chan error)
33 // Write
34 go func() {
35 err := write(ctx, ca, bufs, opt)
36 errCh <- err
37 close(bufs)
38 }()
39
40 // Read
41 go func() {
42 result := make([]byte, opt.MsgSize)
43
44 for original := range bufs {
45 err := read(ctx, cb, original, result)
46 if err != nil {
47 errCh <- err
48 }
49 }
50
51 close(errCh)
52 }()
53
54 return FlattenErrs(GatherErrs(errCh))
55 }
56
57 func read(ctx context.Context, r connctx.Reader, original, result []byte) error {
58 n, err := r.ReadContext(ctx, result)
59 if err != nil {
60 return err
61 }
62 if !bytes.Equal(original, result[:n]) {
63 return fmt.Errorf("%w %#v != %#v", errByteSequenceChanged, original, result)
64 }
65
66 return nil
67 }
68
69 // StressDuplex enables duplex stress testing of a io.ReadWriter.
70 // It checks that packets are received correctly and in order.
71 func StressDuplex(ca io.ReadWriter, cb io.ReadWriter, opt Options) error {
72 return StressDuplexContext(context.Background(), &wrappedReadWriter{ca}, &wrappedReadWriter{cb}, opt)
73 }
74
75 // StressDuplexContext enables duplex stress testing of a io.ReadWriter.
76 // It checks that packets are received correctly and in order.
77 func StressDuplexContext(ctx context.Context, ca connctx.ReadWriter, cb connctx.ReadWriter, opt Options) error {
78 errCh := make(chan error)
79
80 var wg sync.WaitGroup
81 wg.Add(2)
82
83 go func() {
84 defer wg.Done()
85 errCh <- StressContext(ctx, ca, cb, opt)
86 }()
87
88 go func() {
89 defer wg.Done()
90 errCh <- StressContext(ctx, cb, ca, opt)
91 }()
92
93 go func() {
94 wg.Wait()
95 close(errCh)
96 }()
97
98 return FlattenErrs(GatherErrs(errCh))
99 }
100
101 func write(ctx context.Context, c connctx.Writer, bufs chan []byte, opt Options) error {
102 randomizer := initRand()
103 for i := 0; i < opt.MsgCount; i++ {
104 buf, err := randomizer.randBuf(opt.MsgSize)
105 if err != nil {
106 return err
107 }
108 bufs <- buf
109 if _, err = c.WriteContext(ctx, buf); err != nil {
110 return err
111 }
112 }
113 return nil
114 }