serkant.uluderya | e5afeff | 2021-02-23 18:00:23 +0300 | [diff] [blame] | 1 | package internal |
| 2 | |
| 3 | import ( |
| 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 | |
| 13 | func 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 | |
| 27 | func 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 | |
| 43 | func 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 | |
| 53 | func 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 | |
| 65 | func 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 | |
| 76 | func RecordError(ctx context.Context, err error) error { |
| 77 | if err != proto.Nil { |
| 78 | trace.SpanFromContext(ctx).RecordError(ctx, err) |
| 79 | } |
| 80 | return err |
| 81 | } |