2016-10-10 06:29:39 +00:00
|
|
|
package torrent
|
|
|
|
|
|
|
|
import (
|
2018-01-28 04:28:45 +00:00
|
|
|
"context"
|
2017-08-31 04:32:22 +00:00
|
|
|
"fmt"
|
2016-10-10 06:29:39 +00:00
|
|
|
"io"
|
|
|
|
"time"
|
|
|
|
|
|
|
|
"golang.org/x/time/rate"
|
|
|
|
)
|
|
|
|
|
|
|
|
type rateLimitedReader struct {
|
|
|
|
l *rate.Limiter
|
|
|
|
r io.Reader
|
2018-01-28 04:28:45 +00:00
|
|
|
|
|
|
|
// This is the time of the last Read's reservation.
|
|
|
|
lastRead time.Time
|
2016-10-10 06:29:39 +00:00
|
|
|
}
|
|
|
|
|
2018-01-28 04:28:45 +00:00
|
|
|
func (me *rateLimitedReader) Read(b []byte) (n int, err error) {
|
|
|
|
const oldStyle = false // Retained for future reference.
|
|
|
|
if oldStyle {
|
|
|
|
// Wait until we can read at all.
|
|
|
|
if err := me.l.WaitN(context.Background(), 1); err != nil {
|
|
|
|
panic(err)
|
|
|
|
}
|
|
|
|
// Limit the read to within the burst.
|
|
|
|
if me.l.Limit() != rate.Inf && len(b) > me.l.Burst() {
|
|
|
|
b = b[:me.l.Burst()]
|
|
|
|
}
|
|
|
|
n, err = me.r.Read(b)
|
|
|
|
// Pay the piper.
|
|
|
|
now := time.Now()
|
|
|
|
me.lastRead = now
|
|
|
|
if !me.l.ReserveN(now, n-1).OK() {
|
|
|
|
panic(fmt.Sprintf("burst exceeded?: %d", n-1))
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
// Limit the read to within the burst.
|
|
|
|
if me.l.Limit() != rate.Inf && len(b) > me.l.Burst() {
|
|
|
|
b = b[:me.l.Burst()]
|
|
|
|
}
|
|
|
|
n, err = me.r.Read(b)
|
|
|
|
now := time.Now()
|
|
|
|
r := me.l.ReserveN(now, n)
|
|
|
|
if !r.OK() {
|
|
|
|
panic(n)
|
|
|
|
}
|
|
|
|
me.lastRead = now
|
|
|
|
time.Sleep(r.Delay())
|
2016-10-10 06:29:39 +00:00
|
|
|
}
|
|
|
|
return
|
|
|
|
}
|