2017-10-08 18:28:03 +00:00
|
|
|
package limiter
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
|
|
|
"io"
|
|
|
|
|
|
|
|
"github.com/restic/restic/internal/restic"
|
|
|
|
)
|
|
|
|
|
|
|
|
// LimitBackend wraps a Backend and applies rate limiting to Load() and Save()
|
|
|
|
// calls on the backend.
|
|
|
|
func LimitBackend(be restic.Backend, l Limiter) restic.Backend {
|
|
|
|
return rateLimitedBackend{
|
|
|
|
Backend: be,
|
|
|
|
limiter: l,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
type rateLimitedBackend struct {
|
|
|
|
restic.Backend
|
|
|
|
limiter Limiter
|
|
|
|
}
|
|
|
|
|
2018-03-03 13:20:54 +00:00
|
|
|
func (r rateLimitedBackend) Save(ctx context.Context, h restic.Handle, rd restic.RewindReader) error {
|
|
|
|
limited := limitedRewindReader{
|
|
|
|
RewindReader: rd,
|
|
|
|
limited: r.limiter.Upstream(rd),
|
|
|
|
}
|
|
|
|
|
|
|
|
return r.Backend.Save(ctx, h, limited)
|
|
|
|
}
|
|
|
|
|
|
|
|
type limitedRewindReader struct {
|
|
|
|
restic.RewindReader
|
|
|
|
|
|
|
|
limited io.Reader
|
|
|
|
}
|
|
|
|
|
|
|
|
func (l limitedRewindReader) Read(b []byte) (int, error) {
|
|
|
|
return l.limited.Read(b)
|
2017-10-08 18:28:03 +00:00
|
|
|
}
|
|
|
|
|
2018-01-17 04:59:16 +00:00
|
|
|
func (r rateLimitedBackend) Load(ctx context.Context, h restic.Handle, length int, offset int64, consumer func(rd io.Reader) error) error {
|
|
|
|
return r.Backend.Load(ctx, h, length, offset, func(rd io.Reader) error {
|
|
|
|
lrd := limitedReadCloser{
|
|
|
|
limited: r.limiter.Downstream(rd),
|
|
|
|
}
|
|
|
|
return consumer(lrd)
|
|
|
|
})
|
2017-10-08 18:28:03 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
type limitedReadCloser struct {
|
|
|
|
original io.ReadCloser
|
|
|
|
limited io.Reader
|
|
|
|
}
|
|
|
|
|
|
|
|
func (l limitedReadCloser) Read(b []byte) (n int, err error) {
|
|
|
|
return l.limited.Read(b)
|
|
|
|
}
|
|
|
|
|
|
|
|
func (l limitedReadCloser) Close() error {
|
2018-01-17 04:59:16 +00:00
|
|
|
if l.original == nil {
|
|
|
|
return nil
|
|
|
|
}
|
2017-10-08 18:28:03 +00:00
|
|
|
return l.original.Close()
|
|
|
|
}
|
|
|
|
|
|
|
|
var _ restic.Backend = (*rateLimitedBackend)(nil)
|