2016-10-31 23:50:02 +08:00
|
|
|
package swift
|
|
|
|
|
|
|
|
import (
|
|
|
|
"io"
|
|
|
|
"time"
|
|
|
|
)
|
|
|
|
|
2017-05-11 22:39:54 +08:00
|
|
|
var watchdogChunkSize = 1 << 20 // 1 MiB
|
|
|
|
|
2016-10-31 23:50:02 +08:00
|
|
|
// An io.Reader which resets a watchdog timer whenever data is read
|
|
|
|
type watchdogReader struct {
|
2017-05-11 22:39:54 +08:00
|
|
|
timeout time.Duration
|
|
|
|
reader io.Reader
|
|
|
|
timer *time.Timer
|
|
|
|
chunkSize int
|
2016-10-31 23:50:02 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
// Returns a new reader which will kick the watchdog timer whenever data is read
|
|
|
|
func newWatchdogReader(reader io.Reader, timeout time.Duration, timer *time.Timer) *watchdogReader {
|
|
|
|
return &watchdogReader{
|
2017-05-11 22:39:54 +08:00
|
|
|
timeout: timeout,
|
|
|
|
reader: reader,
|
|
|
|
timer: timer,
|
|
|
|
chunkSize: watchdogChunkSize,
|
2016-10-31 23:50:02 +08:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// Read reads up to len(p) bytes into p
|
2017-05-11 22:39:54 +08:00
|
|
|
func (t *watchdogReader) Read(p []byte) (int, error) {
|
|
|
|
//read from underlying reader in chunks not larger than t.chunkSize
|
|
|
|
//while resetting the watchdog timer before every read; the small chunk
|
|
|
|
//size ensures that the timer does not fire when reading a large amount of
|
|
|
|
//data from a slow connection
|
|
|
|
start := 0
|
|
|
|
end := len(p)
|
|
|
|
for start < end {
|
|
|
|
length := end - start
|
|
|
|
if length > t.chunkSize {
|
|
|
|
length = t.chunkSize
|
|
|
|
}
|
|
|
|
|
|
|
|
resetTimer(t.timer, t.timeout)
|
|
|
|
n, err := t.reader.Read(p[start : start+length])
|
|
|
|
start += n
|
|
|
|
if n == 0 || err != nil {
|
|
|
|
return start, err
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2016-10-31 23:50:02 +08:00
|
|
|
resetTimer(t.timer, t.timeout)
|
2017-05-11 22:39:54 +08:00
|
|
|
return start, nil
|
2016-10-31 23:50:02 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
// Check it satisfies the interface
|
|
|
|
var _ io.Reader = &watchdogReader{}
|