Created
May 3, 2023 06:37
-
-
Save marcosuma/e3b0e095b11f1dfff09f6ad24c349bf3 to your computer and use it in GitHub Desktop.
Example of InterceptResponse
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// InterceptResponse intercepts response and create graphql trace | |
func (p *Plugin) InterceptResponse(ctx context.Context, _, _ string, _ map[string]any, response *graphql.Response) *graphql.Response { | |
opts := []ddtrace.StartSpanOption{ | |
tracer.SpanType(ext.SpanTypeGraphQL), | |
tracer.ServiceName(p.ServiceName), | |
} | |
var ( | |
octx *graphql.OperationContext | |
) | |
name := defaultGraphqlOperation | |
if graphql.HasOperationContext(ctx) { | |
// Variables in the operation will be left out of the tags | |
// until obfuscation is implemented in the agent. | |
octx = graphql.GetOperationContext(ctx) | |
if octx.Operation != nil { | |
if octx.Operation.Operation == ast.Subscription { | |
// These are long running queries for a subscription, | |
// remaining open indefinitely until a subscription ends. | |
// Return early and do not create these spans. | |
return response | |
} | |
name = fmt.Sprintf("%s.%s", ext.SpanTypeGraphQL, octx.Operation.Operation) | |
} | |
if octx.RawQuery != "" { | |
opts = append(opts, tracer.ResourceName(octx.RawQuery)) | |
} | |
opts = append(opts, tracer.StartTime(octx.Stats.OperationStart)) | |
} | |
var span ddtrace.Span | |
span, ctx = tracer.StartSpanFromContext(ctx, name, opts...) | |
defer func() { | |
var errs []string | |
for _, err := range graphql.GetErrors(ctx) { | |
errs = append(errs, err.Message) | |
} | |
var err error | |
if len(errs) > 0 { | |
err = fmt.Errorf(strings.Join(errs, ", ")) | |
} | |
span.Finish(tracer.WithError(err)) | |
}() | |
if octx != nil { | |
// Create child spans based on the stats in the operation context. | |
createChildSpan := func(name string, start, finish time.Time) { | |
var childOpts []ddtrace.StartSpanOption | |
childOpts = append(childOpts, tracer.StartTime(start)) | |
childOpts = append(childOpts, tracer.ResourceName(name)) | |
var childSpan ddtrace.Span | |
childSpan, _ = tracer.StartSpanFromContext(ctx, name, childOpts...) | |
childSpan.Finish(tracer.FinishTime(finish)) | |
} | |
createChildSpan(readOp, octx.Stats.Read.Start, octx.Stats.Read.End) | |
createChildSpan(parsingOp, octx.Stats.Parsing.Start, octx.Stats.Parsing.End) | |
createChildSpan(validationOp, octx.Stats.Validation.Start, octx.Stats.Validation.End) | |
} | |
return response | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment