forked from go-kit/kit
-
Notifications
You must be signed in to change notification settings - Fork 0
/
endpoint.go
89 lines (78 loc) · 2.43 KB
/
endpoint.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
package opencensus
import (
"context"
"strconv"
"go.opencensus.io/trace"
"github.com/go-kit/kit/endpoint"
"github.com/go-kit/kit/sd/lb"
)
// TraceEndpointDefaultName is the default endpoint span name to use.
const TraceEndpointDefaultName = "gokit/endpoint"
// TraceEndpoint returns an Endpoint middleware, tracing a Go kit endpoint.
// This endpoint tracer should be used in combination with a Go kit Transport
// tracing middleware, generic OpenCensus transport middleware or custom before
// and after transport functions as service propagation of SpanContext is not
// provided in this middleware.
func TraceEndpoint(name string, options ...EndpointOption) endpoint.Middleware {
if name == "" {
name = TraceEndpointDefaultName
}
cfg := &EndpointOptions{}
for _, o := range options {
o(cfg)
}
return func(next endpoint.Endpoint) endpoint.Endpoint {
return func(ctx context.Context, request interface{}) (response interface{}, err error) {
ctx, span := trace.StartSpan(ctx, name)
if len(cfg.Attributes) > 0 {
span.AddAttributes(cfg.Attributes...)
}
defer span.End()
defer func() {
if err != nil {
if lberr, ok := err.(lb.RetryError); ok {
// handle errors originating from lb.Retry
attrs := make([]trace.Attribute, 0, len(lberr.RawErrors))
for idx, rawErr := range lberr.RawErrors {
attrs = append(attrs, trace.StringAttribute(
"gokit.retry.error."+strconv.Itoa(idx+1), rawErr.Error(),
))
}
span.AddAttributes(attrs...)
span.SetStatus(trace.Status{
Code: trace.StatusCodeUnknown,
Message: lberr.Final.Error(),
})
return
}
// generic error
span.SetStatus(trace.Status{
Code: trace.StatusCodeUnknown,
Message: err.Error(),
})
return
}
// test for business error
if res, ok := response.(endpoint.Failer); ok && res.Failed() != nil {
span.AddAttributes(
trace.StringAttribute("gokit.business.error", res.Failed().Error()),
)
if cfg.IgnoreBusinessError {
span.SetStatus(trace.Status{Code: trace.StatusCodeOK})
return
}
// treating business error as real error in span.
span.SetStatus(trace.Status{
Code: trace.StatusCodeUnknown,
Message: res.Failed().Error(),
})
return
}
// no errors identified
span.SetStatus(trace.Status{Code: trace.StatusCodeOK})
}()
response, err = next(ctx, request)
return
}
}
}