-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
tracer.go
119 lines (95 loc) · 2.68 KB
/
tracer.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
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
package apollotracing
import (
"context"
"sync"
"time"
"github.com/vektah/gqlparser/v2/ast"
"github.com/99designs/gqlgen/graphql"
)
type (
Tracer struct{}
TracingExtension struct {
mu sync.Mutex
Version int `json:"version"`
StartTime time.Time `json:"startTime"`
EndTime time.Time `json:"endTime"`
Duration time.Duration `json:"duration"`
Parsing Span `json:"parsing"`
Validation Span `json:"validation"`
Execution struct {
Resolvers []*ResolverExecution `json:"resolvers"`
} `json:"execution"`
}
Span struct {
StartOffset time.Duration `json:"startOffset"`
Duration time.Duration `json:"duration"`
}
ResolverExecution struct {
Path ast.Path `json:"path"`
ParentType string `json:"parentType"`
FieldName string `json:"fieldName"`
ReturnType string `json:"returnType"`
StartOffset time.Duration `json:"startOffset"`
Duration time.Duration `json:"duration"`
}
)
var _ interface {
graphql.HandlerExtension
graphql.ResponseInterceptor
graphql.FieldInterceptor
} = Tracer{}
func (Tracer) ExtensionName() string {
return "ApolloTracing"
}
func (Tracer) Validate(graphql.ExecutableSchema) error {
return nil
}
func (Tracer) InterceptField(ctx context.Context, next graphql.Resolver) (interface{}, error) {
td, ok := graphql.GetExtension(ctx, "tracing").(*TracingExtension)
if !ok {
return next(ctx)
}
start := graphql.Now()
defer func() {
end := graphql.Now()
rc := graphql.GetOperationContext(ctx)
fc := graphql.GetFieldContext(ctx)
resolver := &ResolverExecution{
Path: fc.Path(),
ParentType: fc.Object,
FieldName: fc.Field.Name,
ReturnType: fc.Field.Definition.Type.String(),
StartOffset: start.Sub(rc.Stats.OperationStart),
Duration: end.Sub(start),
}
td.mu.Lock()
td.Execution.Resolvers = append(td.Execution.Resolvers, resolver)
td.mu.Unlock()
}()
return next(ctx)
}
func (Tracer) InterceptResponse(ctx context.Context, next graphql.ResponseHandler) *graphql.Response {
if !graphql.HasOperationContext(ctx) {
return next(ctx)
}
rc := graphql.GetOperationContext(ctx)
start := rc.Stats.OperationStart
td := &TracingExtension{
Version: 1,
StartTime: start,
Parsing: Span{
StartOffset: rc.Stats.Parsing.Start.Sub(start),
Duration: rc.Stats.Parsing.End.Sub(rc.Stats.Parsing.Start),
},
Validation: Span{
StartOffset: rc.Stats.Validation.Start.Sub(start),
Duration: rc.Stats.Validation.End.Sub(rc.Stats.Validation.Start),
},
}
graphql.RegisterExtension(ctx, "tracing", td)
resp := next(ctx)
end := graphql.Now()
td.EndTime = end
td.Duration = end.Sub(start)
return resp
}