-
Notifications
You must be signed in to change notification settings - Fork 796
/
cortex_util.go
65 lines (54 loc) · 1.74 KB
/
cortex_util.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
package client
import (
context "context"
)
// SendQueryStream wraps the stream's Send() checking if the context is done
// before calling Send().
func SendQueryStream(s Ingester_QueryStreamServer, m *QueryStreamResponse) error {
return sendWithContextErrChecking(s.Context(), func() error {
return s.Send(m)
})
}
func SendMetricsForLabelMatchersStream(s Ingester_MetricsForLabelMatchersStreamServer, m *MetricsForLabelMatchersStreamResponse) error {
return sendWithContextErrChecking(s.Context(), func() error {
return s.Send(m)
})
}
func SendLabelValuesStream(s Ingester_LabelValuesStreamServer, l *LabelValuesStreamResponse) error {
return sendWithContextErrChecking(s.Context(), func() error {
return s.Send(l)
})
}
func SendLabelNamesStream(s Ingester_LabelNamesStreamServer, l *LabelNamesStreamResponse) error {
return sendWithContextErrChecking(s.Context(), func() error {
return s.Send(l)
})
}
func SendAsBatchToStream(totalItems int, streamBatchSize int, fn func(start, end int) error) error {
for i := 0; i < totalItems; i += streamBatchSize {
j := i + streamBatchSize
if j > totalItems {
j = totalItems
}
if err := fn(i, j); err != nil {
return err
}
}
return nil
}
func sendWithContextErrChecking(ctx context.Context, send func() error) error {
// If the context has been canceled or its deadline exceeded, we should return it
// instead of the cryptic error the Send() will return.
if ctxErr := ctx.Err(); ctxErr != nil {
return ctxErr
}
if err := send(); err != nil {
// Experimentally, we've seen the context switching to done after the Send()
// has been called, so here we do recheck the context in case of error.
if ctxErr := ctx.Err(); ctxErr != nil {
return ctxErr
}
return err
}
return nil
}