forked from grafana/tempo
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathasync_sharding.go
More file actions
105 lines (85 loc) · 2.35 KB
/
async_sharding.go
File metadata and controls
105 lines (85 loc) · 2.35 KB
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
96
97
98
99
100
101
102
103
104
105
package pipeline
import (
"context"
"sync"
"github.com/grafana/tempo/modules/frontend/combiner"
"github.com/grafana/tempo/pkg/boundedwaitgroup"
)
type waitGroup interface {
Add(int)
Done()
Wait()
}
// NewAsyncSharderFunc creates a new AsyncResponse that shards requests to the next AsyncRoundTripper[combiner.PipelineResponse]. It creates one
// goroutine per concurrent request.
func NewAsyncSharderFunc(ctx context.Context, concurrentReqs, totalReqs int, reqFn func(i int) Request, next AsyncRoundTripper[combiner.PipelineResponse]) Responses[combiner.PipelineResponse] {
var wg waitGroup
if concurrentReqs <= 0 {
wg = &sync.WaitGroup{}
} else {
bwg := boundedwaitgroup.New(uint(concurrentReqs))
wg = &bwg
}
asyncResp := newAsyncResponse()
go func() {
defer asyncResp.SendComplete()
for i := 0; i < totalReqs; i++ {
req := reqFn(i)
// else check for a request to pass down the pipeline
if req == nil {
continue
}
if err := req.Context().Err(); err != nil {
asyncResp.SendError(err)
continue
}
wg.Add(1)
go func(r Request) {
defer wg.Done()
resp, err := next.RoundTrip(r)
if err != nil {
asyncResp.SendError(err)
return
}
asyncResp.Send(ctx, resp)
}(req)
}
wg.Wait()
}()
return asyncResp
}
// NewAsyncSharderChan creates a new AsyncResponse that shards requests to the next AsyncRoundTripper[combiner.PipelineResponse] using a limited number of goroutines.
func NewAsyncSharderChan(ctx context.Context, concurrentReqs int, reqs <-chan Request, resps Responses[combiner.PipelineResponse], next AsyncRoundTripper[combiner.PipelineResponse]) Responses[combiner.PipelineResponse] {
if concurrentReqs == 0 {
panic("NewAsyncSharderChan: concurrentReqs must be greater than 0")
}
wg := &sync.WaitGroup{}
asyncResp := newAsyncResponse()
for i := 0; i < concurrentReqs; i++ {
wg.Add(1)
go func() {
defer wg.Done()
for req := range reqs {
if err := req.Context().Err(); err != nil {
asyncResp.SendError(err)
continue
}
resp, err := next.RoundTrip(req)
if err != nil {
asyncResp.SendError(err)
continue
}
asyncResp.Send(ctx, resp)
}
}()
}
go func() {
// send any responses back the caller would like to send
if resps != nil {
asyncResp.Send(ctx, resps)
}
wg.Wait()
asyncResp.SendComplete()
}()
return asyncResp
}