10 "github.com/bradfitz/iter"
11 "github.com/stretchr/testify/assert"
12 "github.com/stretchr/testify/require"
13 "golang.org/x/time/rate"
18 func writeN(ws []io.Writer, n int) error {
20 for _, w := range ws[1:] {
22 wn, err := w.Write(b[:n1])
31 wn, err := ws[0].Write(b[:n])
40 func TestRateLimitReaders(t *testing.T) {
49 control := rate.NewLimiter(bytesPerSecond, burst)
50 shared := rate.NewLimiter(bytesPerSecond, burst)
55 wg := sync.WaitGroup{}
58 // When the read was allowed.
61 reads := make(chan read)
62 done := make(chan struct{})
63 for range iter.N(numReaders) {
70 r := rateLimitedReader{
74 b := make([]byte, readSize)
78 case reads <- read{n, r.lastRead}:
92 for _, c := range cs {
103 for range iter.N(writeRounds) {
104 err := writeN(ws, bytesPerRound)
106 log.Printf("error writing: %s", err)
109 written += bytesPerRound
116 started := time.Now()
117 for r := range reads {
118 totalBytesRead += r.N
119 require.False(t, r.At.IsZero())
120 // Copy what the reader should have done with its reservation.
121 res := control.ReserveN(r.At, r.N)
122 // If we don't have to wait with the control, the reader has gone too
125 log.Printf("%d bytes not allowed at %s", r.N, time.Since(started))
129 assert.EqualValues(t, writeRounds*bytesPerRound, totalBytesRead)