File size: 2,032 Bytes
fea99b3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
package tracex

import (
	"context"
	"fmt"
	"runtime/debug"

	"go.opentelemetry.io/otel/attribute"
	otelcodes "go.opentelemetry.io/otel/codes"
	"go.opentelemetry.io/otel/trace"
)

type Options struct {
	OkStatusDescription string
}

var defaultOptions = Options{
	OkStatusDescription: "success",
}

type Option func(*Options)

func WithOkStatusDescription(desc string) Option {
	return func(o *Options) {
		o.OkStatusDescription = desc
	}
}

type Span[T any] struct {
	ctx  context.Context
	span trace.Span
}

func Start[T any](ctx context.Context, tracer trace.Tracer, spanName string, opts ...trace.SpanStartOption) *Span[T] {
	ctx, span := tracer.Start(ctx, spanName, opts...)

	return &Span[T]{
		ctx:  ctx,
		span: span,
	}
}

func (s *Span[T]) Wrap(fn func(ctx context.Context) (T, error), opts ...Option) (T, error) {
	defer func() {
		if r := recover(); r != nil {
			s.span.RecordError(
				fmt.Errorf("panic: %v", r),
				trace.WithStackTrace(true),
				trace.WithAttributes(
					attribute.String("panic.stacktrace", fmt.Sprintf("%v", string(debug.Stack()))),
				),
			)
			s.span.SetStatus(otelcodes.Error, "panic")
			s.span.End()

			panic(r)
		}
	}()

	options := defaultOptions
	for _, opt := range opts {
		opt(&options)
	}

	result, err := fn(s.ctx)
	if err != nil {
		s.span.RecordError(err)
		s.span.SetStatus(otelcodes.Error, err.Error())
	} else {
		s.span.SetStatus(otelcodes.Ok, options.OkStatusDescription)
	}

	s.span.End()

	return result, err
}

type SpanNoValue struct {
	ctx  context.Context
	span trace.Span
}

func StartWithNoValue(ctx context.Context, tracer trace.Tracer, spanName string, opts ...trace.SpanStartOption) *SpanNoValue {
	ctx, span := tracer.Start(ctx, spanName, opts...)

	return &SpanNoValue{
		ctx:  ctx,
		span: span,
	}
}

func (s *SpanNoValue) Wrap(fn func(ctx context.Context) error, opts ...Option) error {
	span := &Span[any]{
		ctx:  s.ctx,
		span: s.span,
	}

	_, err := span.Wrap(func(ctx context.Context) (any, error) {
		return nil, fn(ctx)
	}, opts...)

	return err
}