2
2
mirror of https://github.com/octoleo/restic.git synced 2024-11-26 14:56:29 +00:00
restic/vendor/github.com/ncw/swift/timeout_reader.go

60 lines
1.3 KiB
Go
Raw Normal View History

2017-07-23 12:24:45 +00:00
package swift
import (
"io"
"time"
)
// An io.ReadCloser which obeys an idle timeout
type timeoutReader struct {
reader io.ReadCloser
timeout time.Duration
cancel func()
}
// Returns a wrapper around the reader which obeys an idle
// timeout. The cancel function is called if the timeout happens
func newTimeoutReader(reader io.ReadCloser, timeout time.Duration, cancel func()) *timeoutReader {
return &timeoutReader{
reader: reader,
timeout: timeout,
cancel: cancel,
}
}
// Read reads up to len(p) bytes into p
//
// Waits at most for timeout for the read to complete otherwise returns a timeout
func (t *timeoutReader) Read(p []byte) (int, error) {
// FIXME limit the amount of data read in one chunk so as to not exceed the timeout?
// Do the read in the background
type result struct {
n int
err error
}
done := make(chan result, 1)
go func() {
n, err := t.reader.Read(p)
done <- result{n, err}
}()
// Wait for the read or the timeout
2017-10-22 08:07:36 +00:00
timer := time.NewTimer(t.timeout)
defer timer.Stop()
2017-07-23 12:24:45 +00:00
select {
case r := <-done:
return r.n, r.err
2017-10-22 08:07:36 +00:00
case <-timer.C:
2017-07-23 12:24:45 +00:00
t.cancel()
return 0, TimeoutError
}
panic("unreachable") // for Go 1.0
}
// Close the channel
func (t *timeoutReader) Close() error {
return t.reader.Close()
}
// Check it satisfies the interface
var _ io.ReadCloser = &timeoutReader{}