File: trace.go

package info (click to toggle)
golang-golang-x-exp 0.0~git20231006.7918f67-2
  • links: PTS, VCS
  • area: main
  • in suites: experimental, forky, sid, trixie
  • size: 6,492 kB
  • sloc: ansic: 1,900; objc: 276; sh: 272; asm: 48; makefile: 27
file content (58 lines) | stat: -rw-r--r-- 1,366 bytes parent folder | download | duplicates (4)
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
// Copyright 2021 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package otel

import (
	"context"

	"go.opentelemetry.io/otel/trace"
	"golang.org/x/exp/event"
)

type TraceHandler struct {
	tracer trace.Tracer
}

func NewTraceHandler(t trace.Tracer) *TraceHandler {
	return &TraceHandler{tracer: t}
}

type spanKey struct{}

func (t *TraceHandler) Event(ctx context.Context, ev *event.Event) context.Context {
	switch ev.Kind {
	case event.StartKind:
		name, opts := labelsToSpanStartOptions(ev.Labels)
		octx, span := t.tracer.Start(ctx, name, opts...)
		return context.WithValue(octx, spanKey{}, span)
	case event.EndKind:
		span, ok := ctx.Value(spanKey{}).(trace.Span)
		if !ok {
			panic("End called on context with no span")
		}
		span.End()
		return ctx
	default:
		return ctx
	}
}

func labelsToSpanStartOptions(ls []event.Label) (string, []trace.SpanStartOption) {
	var opts []trace.SpanStartOption
	var name string
	for _, l := range ls {
		switch l.Name {
		case "link":
			opts = append(opts, trace.WithLinks(l.Interface().(trace.Link)))
		case "newRoot":
			opts = append(opts, trace.WithNewRoot())
		case "spanKind":
			opts = append(opts, trace.WithSpanKind(l.Interface().(trace.SpanKind)))
		case "name":
			name = l.String()
		}
	}
	return name, opts
}