github.com/blend/go-sdk@v1.20220411.3/tracing/oauthtrace/tracer.go (about)

     1  /*
     2  
     3  Copyright (c) 2022 - Present. Blend Labs, Inc. All rights reserved
     4  Use of this source code is governed by a MIT license that can be found in the LICENSE file.
     5  
     6  */
     7  
     8  package oauthtrace
     9  
    10  import (
    11  	"context"
    12  	"time"
    13  
    14  	opentracing "github.com/opentracing/opentracing-go"
    15  	"golang.org/x/oauth2"
    16  
    17  	"github.com/blend/go-sdk/oauth"
    18  	"github.com/blend/go-sdk/tracing"
    19  )
    20  
    21  var (
    22  	_ oauth.Tracer        = (*oauthTracer)(nil)
    23  	_ oauth.TraceFinisher = (*oauthTraceFinisher)(nil)
    24  )
    25  
    26  // Tracer returns a request tracer that also injects span context into outgoing headers.
    27  func Tracer(tracer opentracing.Tracer) oauth.Tracer {
    28  	return &oauthTracer{tracer: tracer}
    29  }
    30  
    31  type oauthTracer struct {
    32  	tracer opentracing.Tracer
    33  }
    34  
    35  func (t oauthTracer) Start(ctx context.Context, config *oauth2.Config) oauth.TraceFinisher {
    36  	startOptions := []opentracing.StartSpanOption{
    37  		opentracing.Tag{Key: tracing.TagKeySpanType, Value: tracing.SpanTypeHTTP},
    38  		tracing.TagMeasured(),
    39  		opentracing.StartTime(time.Now().UTC()),
    40  	}
    41  	span, _ := tracing.StartSpanFromContext(ctx, t.tracer, tracing.OperationHTTPRequest, startOptions...)
    42  	return oauthTraceFinisher{span: span}
    43  }
    44  
    45  type oauthTraceFinisher struct {
    46  	span opentracing.Span
    47  }
    48  
    49  func (of oauthTraceFinisher) Finish(ctx context.Context, config *oauth2.Config, result *oauth.Result, err error) {
    50  	if of.span == nil {
    51  		return
    52  	}
    53  	tracing.SpanError(of.span, err)
    54  	if result != nil {
    55  		of.span.SetTag(tracing.TagKeyOAuthUsername, result.Profile.Email)
    56  	}
    57  	of.span.Finish()
    58  }