66 lines
1.3 KiB
Go
66 lines
1.3 KiB
Go
|
|
package transfer
|
||
|
|
|
||
|
|
import (
|
||
|
|
"context"
|
||
|
|
"io"
|
||
|
|
"time"
|
||
|
|
)
|
||
|
|
|
||
|
|
// progressReader checks ctx before every chunk (cancellation inside a file:
|
||
|
|
// N-P1-7) and reports bytes read. Size lets pkg/sftp pick its concurrent
|
||
|
|
// ReadFrom path.
|
||
|
|
type progressReader struct {
|
||
|
|
ctx context.Context
|
||
|
|
r io.Reader
|
||
|
|
size int64
|
||
|
|
n int64
|
||
|
|
onRead func(total int64)
|
||
|
|
}
|
||
|
|
|
||
|
|
func (r *progressReader) Read(p []byte) (int, error) {
|
||
|
|
if err := r.ctx.Err(); err != nil {
|
||
|
|
return 0, err
|
||
|
|
}
|
||
|
|
n, err := r.r.Read(p)
|
||
|
|
if n > 0 {
|
||
|
|
r.n += int64(n)
|
||
|
|
if r.onRead != nil {
|
||
|
|
r.onRead(r.n)
|
||
|
|
}
|
||
|
|
}
|
||
|
|
return n, err
|
||
|
|
}
|
||
|
|
|
||
|
|
func (r *progressReader) Size() int64 { return r.size }
|
||
|
|
|
||
|
|
// defaultProgressInterval bounds how often Hooks.Progress is called.
|
||
|
|
const defaultProgressInterval = 50 * time.Millisecond
|
||
|
|
|
||
|
|
// emitter throttles progress callbacks.
|
||
|
|
type emitter struct {
|
||
|
|
fn func(Progress)
|
||
|
|
every time.Duration
|
||
|
|
last time.Time
|
||
|
|
p Progress
|
||
|
|
}
|
||
|
|
|
||
|
|
func newEmitter(fn func(Progress), every time.Duration) *emitter {
|
||
|
|
if every <= 0 {
|
||
|
|
every = defaultProgressInterval
|
||
|
|
}
|
||
|
|
return &emitter{fn: fn, every: every}
|
||
|
|
}
|
||
|
|
|
||
|
|
// emit calls fn if the interval has passed or force is set.
|
||
|
|
func (e *emitter) emit(force bool) {
|
||
|
|
if e.fn == nil {
|
||
|
|
return
|
||
|
|
}
|
||
|
|
now := time.Now()
|
||
|
|
if !force && now.Sub(e.last) < e.every {
|
||
|
|
return
|
||
|
|
}
|
||
|
|
e.last = now
|
||
|
|
e.fn(e.p)
|
||
|
|
}
|