2017-06-13 21:42:51 +00:00
|
|
|
package progress
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
2017-06-16 22:49:03 +00:00
|
|
|
"io"
|
2017-06-13 21:42:51 +00:00
|
|
|
"sync"
|
|
|
|
)
|
|
|
|
|
|
|
|
type MultiReader struct {
|
|
|
|
mu sync.Mutex
|
2017-06-17 05:12:27 +00:00
|
|
|
main Reader
|
2017-06-13 21:42:51 +00:00
|
|
|
initialized bool
|
|
|
|
done chan struct{}
|
2017-06-14 00:15:55 +00:00
|
|
|
writers map[*progressWriter]func()
|
2017-06-13 21:42:51 +00:00
|
|
|
}
|
|
|
|
|
2017-06-17 05:12:27 +00:00
|
|
|
func NewMultiReader(pr Reader) *MultiReader {
|
2017-06-13 21:42:51 +00:00
|
|
|
mr := &MultiReader{
|
2017-06-14 00:15:55 +00:00
|
|
|
main: pr,
|
|
|
|
writers: make(map[*progressWriter]func()),
|
|
|
|
done: make(chan struct{}),
|
2017-06-13 21:42:51 +00:00
|
|
|
}
|
|
|
|
return mr
|
|
|
|
}
|
|
|
|
|
2017-06-17 05:12:27 +00:00
|
|
|
func (mr *MultiReader) Reader(ctx context.Context) Reader {
|
2017-06-13 21:42:51 +00:00
|
|
|
mr.mu.Lock()
|
|
|
|
defer mr.mu.Unlock()
|
|
|
|
|
2017-06-14 00:15:55 +00:00
|
|
|
pr, ctx, closeWriter := NewContext(ctx)
|
2017-06-17 05:12:27 +00:00
|
|
|
pw, _, ctx := FromContext(ctx)
|
2017-06-13 21:42:51 +00:00
|
|
|
|
|
|
|
w := pw.(*progressWriter)
|
2017-06-14 00:15:55 +00:00
|
|
|
mr.writers[w] = closeWriter
|
2017-06-13 21:42:51 +00:00
|
|
|
|
|
|
|
go func() {
|
|
|
|
select {
|
|
|
|
case <-ctx.Done():
|
|
|
|
case <-mr.done:
|
|
|
|
}
|
|
|
|
mr.mu.Lock()
|
|
|
|
defer mr.mu.Unlock()
|
|
|
|
delete(mr.writers, w)
|
|
|
|
}()
|
|
|
|
|
|
|
|
if !mr.initialized {
|
|
|
|
go mr.handle()
|
|
|
|
mr.initialized = true
|
|
|
|
}
|
|
|
|
|
|
|
|
return pr
|
|
|
|
}
|
|
|
|
|
|
|
|
func (mr *MultiReader) handle() error {
|
|
|
|
for {
|
|
|
|
p, err := mr.main.Read(context.TODO())
|
|
|
|
if err != nil {
|
2017-06-16 22:49:03 +00:00
|
|
|
if err == io.EOF {
|
|
|
|
mr.mu.Lock()
|
2017-06-17 05:12:27 +00:00
|
|
|
for w, c := range mr.writers {
|
|
|
|
w.Close()
|
|
|
|
c()
|
2017-06-16 22:49:03 +00:00
|
|
|
}
|
|
|
|
mr.mu.Unlock()
|
|
|
|
return nil
|
|
|
|
}
|
2017-06-13 21:42:51 +00:00
|
|
|
return err
|
|
|
|
}
|
|
|
|
mr.mu.Lock()
|
2017-06-16 22:49:03 +00:00
|
|
|
for _, p := range p {
|
2017-06-17 05:12:27 +00:00
|
|
|
for w := range mr.writers {
|
2017-06-28 20:59:07 +00:00
|
|
|
w.writeRawProgress(p)
|
2017-06-14 00:15:55 +00:00
|
|
|
}
|
2017-06-13 21:42:51 +00:00
|
|
|
}
|
|
|
|
mr.mu.Unlock()
|
|
|
|
}
|
|
|
|
}
|