Skip to content

Commit

Permalink
improve detaching a context
Browse files Browse the repository at this point in the history
  • Loading branch information
shogo82148 committed Apr 3, 2021
1 parent 9f6dcd3 commit ec0b6d9
Showing 1 changed file with 33 additions and 1 deletion.
34 changes: 33 additions & 1 deletion xray/segment.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import (
"fmt"
"net/http"
"os"
"reflect"
"strings"
"sync"
"time"
Expand Down Expand Up @@ -743,8 +744,39 @@ func AddAnnotationFloat64(ctx context.Context, key string, value float64) {
}

// DetachContextSegment returns a new context with the existing segment.
// All values associated with ctx are also associated with the new context.
// This is useful for creating background tasks which won't be cancelled
// when a request completes.
func DetachContextSegment(ctx context.Context) context.Context {
return context.WithValue(context.Background(), segmentContextKey, ContextSegment(ctx))
return &detachedContext{Context: ctx}
}

type detachedContext struct {
context.Context
}

func (*detachedContext) Deadline() (deadline time.Time, ok bool) {
return
}

func (*detachedContext) Done() <-chan struct{} {
return nil
}

func (*detachedContext) Err() error {
return nil
}

func (ctx *detachedContext) String() string {
return contextName(ctx.Context) + ".Detached"
}

func contextName(c context.Context) string {
type stringer interface {
String() string
}
if s, ok := c.(stringer); ok {
return s.String()
}
return reflect.TypeOf(c).String()
}

0 comments on commit ec0b6d9

Please sign in to comment.