-
Notifications
You must be signed in to change notification settings - Fork 0
/
scatter_gather.go
95 lines (86 loc) · 1.92 KB
/
scatter_gather.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
package main
import (
"context"
"errors"
"sync"
"time"
)
type scatterGather[B Backend, R any] struct {
backends []B
start time.Time
wg sync.WaitGroup
out chan R
maxWait time.Duration
}
func (sg *scatterGather[B, R]) scatter(ctx context.Context, forEach func(context.Context, B) (*R, error)) error {
sg.start = time.Now()
sg.out = make(chan R, 1)
for _, backend := range sg.backends {
if backend.CB() != nil && !backend.CB().Ready() {
continue
}
sg.wg.Add(1)
go func(target B) {
defer sg.wg.Done()
select {
case <-ctx.Done():
log.Errorw("context is done before completing scatter", "err", ctx.Err())
return
default:
}
cctx, cancel := context.WithTimeout(ctx, sg.maxWait)
sout, err := forEach(cctx, target)
cancel()
if target.CB() != nil {
err = target.CB().Done(cctx, err)
}
if err != nil {
if errors.Is(err, context.Canceled) {
log.Debugw("Scatter on target canceled", "target", target.URL().Host)
} else if errors.Is(err, context.DeadlineExceeded) {
log.Debugw("failed to scatter on target because context deadline exceeded", "target", target.URL().Host, "maxWait", sg.maxWait)
} else {
log.Errorw("failed to scatter on target", "target", target.URL().Host, "err", err, "maxWait", sg.maxWait)
}
return
}
if sout != nil {
select {
case <-ctx.Done():
case sg.out <- *sout:
}
}
}(backend)
}
go func() {
defer close(sg.out)
sg.wg.Wait()
}()
return nil
}
func (sg *scatterGather[_, R]) gather(ctx context.Context) <-chan R {
gout := make(chan R, 1)
go func() {
defer func() {
close(gout)
log.Debugw("Completed scatter gather", "elapsed", time.Since(sg.start))
}()
for {
select {
case <-ctx.Done():
return
case r, ok := <-sg.out:
if !ok {
return
}
select {
case <-ctx.Done():
return
case gout <- r:
continue
}
}
}
}()
return gout
}