blob: 894382b805b3c6f01f5399c10d552d8acbb25e8b [file] [log] [blame]
Joey Armstronge8c091f2023-01-17 16:56:26 -05001package internal
2
3import (
4 "context"
5 "time"
6
7 "github.com/go-redis/redis/v8/internal/proto"
8 "github.com/go-redis/redis/v8/internal/util"
9 "go.opentelemetry.io/otel/api/global"
10 "go.opentelemetry.io/otel/api/trace"
11)
12
13func Sleep(ctx context.Context, dur time.Duration) error {
14 return WithSpan(ctx, "time.Sleep", func(ctx context.Context, span trace.Span) error {
15 t := time.NewTimer(dur)
16 defer t.Stop()
17
18 select {
19 case <-t.C:
20 return nil
21 case <-ctx.Done():
22 return ctx.Err()
23 }
24 })
25}
26
27func ToLower(s string) string {
28 if isLower(s) {
29 return s
30 }
31
32 b := make([]byte, len(s))
33 for i := range b {
34 c := s[i]
35 if c >= 'A' && c <= 'Z' {
36 c += 'a' - 'A'
37 }
38 b[i] = c
39 }
40 return util.BytesToString(b)
41}
42
43func isLower(s string) bool {
44 for i := 0; i < len(s); i++ {
45 c := s[i]
46 if c >= 'A' && c <= 'Z' {
47 return false
48 }
49 }
50 return true
51}
52
53func Unwrap(err error) error {
54 u, ok := err.(interface {
55 Unwrap() error
56 })
57 if !ok {
58 return nil
59 }
60 return u.Unwrap()
61}
62
63//------------------------------------------------------------------------------
64
65func WithSpan(ctx context.Context, name string, fn func(context.Context, trace.Span) error) error {
66 if span := trace.SpanFromContext(ctx); !span.IsRecording() {
67 return fn(ctx, span)
68 }
69
70 ctx, span := global.Tracer("github.com/go-redis/redis").Start(ctx, name)
71 defer span.End()
72
73 return fn(ctx, span)
74}
75
76func RecordError(ctx context.Context, err error) error {
77 if err != proto.Nil {
78 trace.SpanFromContext(ctx).RecordError(ctx, err)
79 }
80 return err
81}