-
Notifications
You must be signed in to change notification settings - Fork 3
/
retry.go
103 lines (91 loc) · 2.51 KB
/
retry.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
96
97
98
99
100
101
102
103
package ydb
import (
"context"
"fmt"
"go.opentelemetry.io/otel/attribute"
"go.opentelemetry.io/otel/codes"
"github.com/ydb-platform/ydb-go-sdk/v3/trace"
)
type (
ctxRetryFunctionIDKey struct{}
ctxRetryFieldsKey struct{}
ctxNoTraceRetryKey struct{}
fieldsStore struct {
fields []attribute.KeyValue
}
)
func withFunctionID(ctx context.Context, functionID string) context.Context {
return context.WithValue(ctx, ctxRetryFunctionIDKey{}, functionID)
}
func functionID(ctx context.Context) string {
if functionID, has := ctx.Value(ctxRetryFunctionIDKey{}).(string); has {
return functionID
}
return ""
}
func noTraceRetry(ctx context.Context) context.Context {
return context.WithValue(ctx, ctxNoTraceRetryKey{}, true)
}
func isTraceRetry(ctx context.Context) bool {
if noTrace, has := ctx.Value(ctxNoTraceRetryKey{}).(bool); has {
return !noTrace
}
return true
}
func fieldsStoreFromContext(ctx *context.Context) *fieldsStore {
if store, has := (*ctx).Value(ctxRetryFieldsKey{}).(*fieldsStore); has {
return store
}
store := &fieldsStore{}
*ctx = context.WithValue(*ctx, ctxRetryFieldsKey{}, store)
return store
}
func fieldsFromStore(ctx context.Context) []attribute.KeyValue {
if holder, has := ctx.Value(ctxRetryFieldsKey{}).(*fieldsStore); has {
return holder.fields
}
return nil
}
func Retry(opts ...Option) trace.Retry {
c := makeConfig(opts...)
return retry(c)
}
func retry(cfg *config) (t trace.Retry) {
t.OnRetry = func(info trace.RetryLoopStartInfo) func(trace.RetryLoopDoneInfo) {
if cfg.detailer.Details()&trace.RetryEvents != 0 && isTraceRetry(*info.Context) { //nolint:nestif
operationName := info.Label
if operationName == "" {
operationName = info.Call.FunctionID()
}
if functionID := functionID(*info.Context); functionID != "" {
operationName = functionID
}
start := childSpanWithReplaceCtx(
cfg.tracer,
info.Context,
operationName,
attribute.Bool("idempotent", info.Idempotent),
)
if info.NestedCall {
start.RecordError(fmt.Errorf("nested call"))
}
ctx := *info.Context
return func(info trace.RetryLoopDoneInfo) {
start.SetAttributes(
attribute.Int("attempts", info.Attempts),
attribute.Bool(errorAttribute, info.Error != nil),
)
if fields := fieldsFromStore(ctx); len(fields) > 0 {
start.SetAttributes(fields...)
}
if info.Error != nil {
start.RecordError(info.Error)
start.SetStatus(codes.Error, info.Error.Error())
}
start.End()
}
}
return nil
}
return t
}