-
Notifications
You must be signed in to change notification settings - Fork 9
/
span.go
73 lines (56 loc) · 1.84 KB
/
span.go
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
// Copyright 2022 Namespace Labs Inc; All rights reserved.
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
package postgres
import (
"context"
"errors"
"io"
"github.com/jackc/pgx/v4"
"go.opentelemetry.io/otel/codes"
semconv "go.opentelemetry.io/otel/semconv/v1.17.0"
"go.opentelemetry.io/otel/trace"
statuscodes "google.golang.org/grpc/codes"
"namespacelabs.dev/foundation/framework/rpcerrors"
)
func withSpan(ctx context.Context, tracer trace.Tracer, name, sql string, f func(context.Context) error) error {
if tracer == nil {
return f(ctx)
}
options := []trace.SpanStartOption{trace.WithSpanKind(trace.SpanKindClient)}
if sql != "" {
options = append(options, trace.WithAttributes(semconv.DBStatementKey.String(sql)))
}
ctx, span := tracer.Start(ctx, name, options...)
defer span.End()
err := checkErr(f(ctx))
if err != nil && !errors.Is(err, io.EOF) && !errors.Is(err, pgx.ErrNoRows) {
span.RecordError(err)
span.SetStatus(codes.Error, err.Error())
}
return err
}
func returnWithSpan[T any](ctx context.Context, tracer trace.Tracer, name, sql string, f func(context.Context) (T, error)) (T, error) {
if tracer == nil {
return f(ctx)
}
options := []trace.SpanStartOption{trace.WithSpanKind(trace.SpanKindClient)}
if sql != "" {
options = append(options, trace.WithAttributes(semconv.DBStatementKey.String(sql)))
}
ctx, span := tracer.Start(ctx, name, options...)
defer span.End()
value, err := f(ctx)
err = checkErr(err)
if err != nil && !errors.Is(err, io.EOF) && !errors.Is(err, pgx.ErrNoRows) {
span.RecordError(err)
span.SetStatus(codes.Error, err.Error())
}
return value, err
}
func checkErr(err error) error {
if errors.Is(err, io.ErrUnexpectedEOF) {
return rpcerrors.Wrap(statuscodes.Unavailable, err)
}
return err
}