aggregator.go 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. /*
  2. Copyright (c) 2014 VMware, Inc. All Rights Reserved.
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package progress
  14. import "sync"
  15. type Aggregator struct {
  16. downstream Sinker
  17. upstream chan (<-chan Report)
  18. done chan struct{}
  19. w sync.WaitGroup
  20. }
  21. func NewAggregator(s Sinker) *Aggregator {
  22. a := &Aggregator{
  23. downstream: s,
  24. upstream: make(chan (<-chan Report)),
  25. done: make(chan struct{}),
  26. }
  27. a.w.Add(1)
  28. go a.loop()
  29. return a
  30. }
  31. func (a *Aggregator) loop() {
  32. defer a.w.Done()
  33. dch := a.downstream.Sink()
  34. defer close(dch)
  35. for {
  36. select {
  37. case uch := <-a.upstream:
  38. // Drain upstream channel
  39. for e := range uch {
  40. dch <- e
  41. }
  42. case <-a.done:
  43. return
  44. }
  45. }
  46. }
  47. func (a *Aggregator) Sink() chan<- Report {
  48. ch := make(chan Report)
  49. a.upstream <- ch
  50. return ch
  51. }
  52. // Done marks the aggregator as done. No more calls to Sink() may be made and
  53. // the downstream progress report channel will be closed when Done() returns.
  54. func (a *Aggregator) Done() {
  55. close(a.done)
  56. a.w.Wait()
  57. }