Compare commits

..

20 Commits
v3.10.8 ... v3

Author SHA1 Message Date
77fe9cbef6 fixup trace span names
Some checks failed
build / test (push) Failing after 1s
build / lint (push) Failing after 0s
codeql / analyze (go) (push) Failing after 0s
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2024-11-22 16:06:59 +03:00
c59902201d add_labels (#120)
Some checks failed
codeql / analyze (go) (push) Failing after 56s
build / test (push) Failing after 4m59s
build / lint (push) Successful in 9m34s
closes #119

Reviewed-on: #120
Co-authored-by: Evstigneev Denis <danteevstigneev@yandex.ru>
Co-committed-by: Evstigneev Denis <danteevstigneev@yandex.ru>
2024-11-19 00:34:04 +03:00
0981f89f60 Merge pull request 'fix deps' (#118) from devstigneev/micro-store-redis:v3_1 into v3
Some checks failed
codeql / analyze (go) (push) Failing after 46s
build / test (push) Failing after 4m56s
build / lint (push) Successful in 9m31s
Reviewed-on: #118
2024-10-15 11:56:58 +03:00
332fe5f4d4 fix deps
Some checks failed
automerge / automerge (pull_request) Has been skipped
autoapprove / autoapprove (pull_request) Successful in 8s
dependabot-automerge / automerge (pull_request) Has been skipped
codeql / analyze (go) (pull_request) Failing after 49s
prbuild / test (pull_request) Has been cancelled
prbuild / lint (pull_request) Has been cancelled
2024-10-14 18:56:37 +03:00
757fe0245b update all
Some checks failed
codeql / analyze (go) (push) Failing after 42s
build / test (push) Failing after 4m53s
build / lint (push) Successful in 9m28s
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2024-10-14 17:49:38 +03:00
27eccc1ed2 fixup nil pointer assign
Some checks failed
codeql / analyze (go) (push) Failing after 41s
build / test (push) Failing after 4m52s
build / lint (push) Successful in 9m29s
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2024-10-08 16:52:26 +03:00
7c641fa8ac fixup nil pointer assign
Some checks failed
codeql / analyze (go) (push) Failing after 39s
build / test (push) Failing after 4m55s
build / lint (push) Has been cancelled
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2024-10-08 16:47:27 +03:00
24c9f20196 toolchain go1.22.4 (#116)
Some checks failed
codeql / analyze (go) (push) Failing after 44s
build / test (push) Failing after 4m55s
build / lint (push) Successful in 9m29s
- go mod tidy
- fix version redis
- retract (
  v9.5.3 // This version was accidentally released.
) from github.com/redis/go-redis/extra/rediscmd/v9@v9.5.3

Reviewed-on: #116
Co-authored-by: Evstigneev Denis <danteevstigneev@yandex.ru>
Co-committed-by: Evstigneev Denis <danteevstigneev@yandex.ru>
2024-10-08 13:07:46 +03:00
953b5b0021 fixup default redis default local addr
Some checks failed
codeql / analyze (go) (push) Failing after 37s
build / test (push) Failing after 4m54s
build / lint (push) Successful in 9m29s
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2024-10-06 18:49:50 +03:00
87e2e2b947 switch to universal client
Some checks failed
codeql / analyze (go) (push) Failing after 1m30s
build / test (push) Failing after 5m13s
build / lint (push) Successful in 9m40s
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2024-10-05 16:11:46 +03:00
256e61a437 fixup slice override
Some checks failed
build / test (push) Failing after 7s
build / lint (push) Failing after 7s
codeql / analyze (go) (push) Failing after 10s
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2024-09-25 15:27:53 +03:00
f9cdd41c94 Merge pull request 'changed MetricPrefix to Labels' (#112) from devstigneev/micro-store-redis:v3 into v3
Some checks failed
build / test (push) Failing after 10s
build / lint (push) Failing after 10s
codeql / analyze (go) (push) Failing after 10s
Reviewed-on: #112
Reviewed-by: Василий Толстов <v.tolstov@unistack.org>
2024-09-23 18:23:27 +03:00
ecad15fe17 changed MetricPrefix to Labels
Some checks failed
automerge / automerge (pull_request) Has been skipped
autoapprove / autoapprove (pull_request) Failing after 5s
dependabot-automerge / automerge (pull_request) Has been skipped
codeql / analyze (go) (pull_request) Has been cancelled
prbuild / test (pull_request) Has been cancelled
prbuild / lint (pull_request) Has been cancelled
2024-09-21 14:01:04 +03:00
fa3d18b353 tracing commented redis.dial
Some checks failed
build / test (push) Failing after 21s
build / lint (push) Successful in 20s
codeql / analyze (go) (push) Failing after 39s
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2024-07-18 11:28:45 +03:00
2f3951773f cleanup trace spans
Some checks failed
build / lint (push) Successful in 24s
build / test (push) Failing after 1m25s
codeql / analyze (go) (push) Failing after 1m53s
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2024-07-05 23:11:12 +03:00
b263e14032 cleanup trace spans from cluster slots command
Some checks failed
build / lint (push) Successful in 22s
build / test (push) Failing after 1m30s
codeql / analyze (go) (push) Failing after 1m51s
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2024-07-05 13:44:29 +03:00
518cc1db73 fixup duplicate nested redis span
Some checks failed
build / lint (push) Successful in 22s
build / test (push) Failing after 1m29s
codeql / analyze (go) (push) Failing after 1m52s
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2024-07-05 12:59:05 +03:00
4484cd34ec unify span names
Some checks failed
build / lint (push) Successful in 23s
build / test (push) Failing after 1m29s
codeql / analyze (go) (push) Failing after 1m55s
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2024-07-05 09:16:08 +03:00
7bceeee6bf unify span names
Some checks failed
build / lint (push) Successful in 23s
build / test (push) Failing after 1m31s
codeql / analyze (go) (push) Failing after 1m52s
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2024-07-05 08:57:29 +03:00
aed9512b93 improve metrics and tracing
Some checks failed
build / lint (push) Successful in 40s
build / test (push) Failing after 1m43s
codeql / analyze (go) (push) Failing after 3m9s
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2024-07-04 15:13:19 +03:00
8 changed files with 588 additions and 246 deletions

1
.gitignore vendored Normal file
View File

@ -0,0 +1 @@
.idea

15
go.mod
View File

@ -1,14 +1,19 @@
module go.unistack.org/micro-store-redis/v3 module go.unistack.org/micro-store-redis/v3
go 1.20 go 1.22
toolchain go1.22.4
require ( require (
github.com/redis/go-redis/v9 v9.2.1 github.com/redis/go-redis/extra/rediscmd/v9 v9.6.2
go.unistack.org/micro/v3 v3.10.62 github.com/redis/go-redis/v9 v9.6.2
go.unistack.org/micro/v3 v3.10.97
) )
require ( require (
github.com/cespare/xxhash/v2 v2.2.0 // indirect github.com/cespare/xxhash/v2 v2.3.0 // indirect
github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f // indirect github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f // indirect
github.com/patrickmn/go-cache v2.1.0+incompatible // indirect github.com/google/go-cmp v0.6.0 // indirect
go.unistack.org/micro-proto/v3 v3.4.1 // indirect
google.golang.org/protobuf v1.35.1 // indirect
) )

24
go.sum
View File

@ -1,12 +1,20 @@
github.com/bsm/ginkgo/v2 v2.12.0 h1:Ny8MWAHyOepLGlLKYmXG4IEkioBysk6GpaRTLC8zwWs= github.com/bsm/ginkgo/v2 v2.12.0 h1:Ny8MWAHyOepLGlLKYmXG4IEkioBysk6GpaRTLC8zwWs=
github.com/bsm/ginkgo/v2 v2.12.0/go.mod h1:SwYbGRRDovPVboqFv0tPTcG1sN61LM1Z4ARdbAV9g4c=
github.com/bsm/gomega v1.27.10 h1:yeMWxP2pV2fG3FgAODIY8EiRE3dy0aeFYt4l7wh6yKA= github.com/bsm/gomega v1.27.10 h1:yeMWxP2pV2fG3FgAODIY8EiRE3dy0aeFYt4l7wh6yKA=
github.com/cespare/xxhash/v2 v2.2.0 h1:DC2CZ1Ep5Y4k3ZQ899DldepgrayRUGE6BBZ/cd9Cj44= github.com/bsm/gomega v1.27.10/go.mod h1:JyEr/xRbxbtgWNi8tIEVPUYZ5Dzef52k01W3YH0H+O0=
github.com/cespare/xxhash/v2 v2.2.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs= github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs=
github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=
github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f h1:lO4WD4F/rVNCu3HqELle0jiPLLBs70cWOduZpkS1E78= github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f h1:lO4WD4F/rVNCu3HqELle0jiPLLBs70cWOduZpkS1E78=
github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f/go.mod h1:cuUVRXasLTGF7a8hSLbxyZXjz+1KgoB3wDUb6vlszIc= github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f/go.mod h1:cuUVRXasLTGF7a8hSLbxyZXjz+1KgoB3wDUb6vlszIc=
github.com/patrickmn/go-cache v2.1.0+incompatible h1:HRMgzkcYKYpi3C8ajMPV8OFXaaRUnok+kx1WdO15EQc= github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI=
github.com/patrickmn/go-cache v2.1.0+incompatible/go.mod h1:3Qf8kWWT7OJRJbdiICTKqZju1ZixQ/KpMGzzAfe6+WQ= github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
github.com/redis/go-redis/v9 v9.2.1 h1:WlYJg71ODF0dVspZZCpYmoF1+U1Jjk9Rwd7pq6QmlCg= github.com/redis/go-redis/extra/rediscmd/v9 v9.6.2 h1:oBlErygFka9FAVfowzW7sRUfB7n31YX0aFzfaOflM3w=
github.com/redis/go-redis/v9 v9.2.1/go.mod h1:hdY0cQFCN4fnSYT6TkisLufl/4W5UIXyv0b/CLO2V2M= github.com/redis/go-redis/extra/rediscmd/v9 v9.6.2/go.mod h1:jYLUE5tC8UsFnpSclhEjZlFLMMtHH4jTfFMnshNWkoo=
go.unistack.org/micro/v3 v3.10.62 h1:PCwLSt3W53UGosH/5qU3kU0iJxK8jlKOm9p4v/Zti5o= github.com/redis/go-redis/v9 v9.6.2 h1:w0uvkRbc9KpgD98zcvo5IrVUsn0lXpRMuhNgiHDJzdk=
go.unistack.org/micro/v3 v3.10.62/go.mod h1:erMgt3Bl7vQQ0e9UpQyR5NlLiZ9pKeEJ9+1tfYFaqUg= github.com/redis/go-redis/v9 v9.6.2/go.mod h1:0C0c6ycQsdpVNQpxb1njEQIqkx5UcsM8FJCQLgE9+RA=
go.unistack.org/micro-proto/v3 v3.4.1 h1:UTjLSRz2YZuaHk9iSlVqqsA50JQNAEK2ZFboGqtEa9Q=
go.unistack.org/micro-proto/v3 v3.4.1/go.mod h1:okx/cnOhzuCX0ggl/vToatbCupi0O44diiiLLsZ93Zo=
go.unistack.org/micro/v3 v3.10.97 h1:8l7fv+i06/PjPrBBhRC/ZQkWGIOuHPg3jJN0vktYE78=
go.unistack.org/micro/v3 v3.10.97/go.mod h1:YzMldzHN9Ei+zy5t/Psu7RUWDZwUfrNYiStSQtTz90g=
google.golang.org/protobuf v1.35.1 h1:m3LfL6/Ca+fqnjnlqQXNpFPABW1UD7mjh8KO2mKFytA=
google.golang.org/protobuf v1.35.1/go.mod h1:9fA7Ob0pmnwhb644+1+CVWFRbNajQ6iRojtC/QF5bRE=

View File

@ -1,18 +1,67 @@
package redis package redis
import ( import (
"github.com/redis/go-redis/v9" goredis "github.com/redis/go-redis/v9"
"go.unistack.org/micro/v3/logger"
"go.unistack.org/micro/v3/meter"
"go.unistack.org/micro/v3/store" "go.unistack.org/micro/v3/store"
"go.unistack.org/micro/v3/tracer"
) )
type configKey struct{} type configKey struct{}
func Config(c *redis.Options) store.Option { func Config(c *goredis.Options) store.Option {
return store.SetOption(configKey{}, c) return store.SetOption(configKey{}, c)
} }
type clusterConfigKey struct{} type clusterConfigKey struct{}
func ClusterConfig(c *redis.ClusterOptions) store.Option { func ClusterConfig(c *goredis.ClusterOptions) store.Option {
return store.SetOption(clusterConfigKey{}, c) return store.SetOption(clusterConfigKey{}, c)
} }
type universalConfigKey struct{}
func UniversalConfig(c *goredis.UniversalOptions) store.Option {
return store.SetOption(universalConfigKey{}, c)
}
var (
labelHost = "redis_host"
labelName = "redis_name"
)
// Options struct holds wrapper options
type Options struct {
Logger logger.Logger
Meter meter.Meter
Tracer tracer.Tracer
RedisHost string
RedisName string
}
// Option func signature
type Option func(*Options)
// NewOptions create new Options struct from provided option slice
func NewOptions(opts ...Option) Options {
options := Options{
Logger: logger.DefaultLogger,
Meter: meter.DefaultMeter,
Tracer: tracer.DefaultTracer,
}
for _, o := range opts {
o(&options)
}
options.Meter = options.Meter.Clone(
meter.Labels(
labelHost, options.RedisHost,
labelName, options.RedisName),
)
options.Logger = options.Logger.Clone(logger.WithAddCallerSkipCount(1))
return options
}

507
redis.go
View File

@ -2,22 +2,21 @@ package redis
import ( import (
"context" "context"
"fmt" "errors"
"reflect" "reflect"
"strings" "strings"
"time" "time"
redis "github.com/redis/go-redis/v9" goredis "github.com/redis/go-redis/v9"
"go.unistack.org/micro/v3/semconv" "go.unistack.org/micro/v3/semconv"
"go.unistack.org/micro/v3/store" "go.unistack.org/micro/v3/store"
"go.unistack.org/micro/v3/tracer"
pool "go.unistack.org/micro/v3/util/xpool" pool "go.unistack.org/micro/v3/util/xpool"
) )
var ( var (
DefaultPathSeparator = "/" DefaultPathSeparator = "/"
DefaultClusterOptions = &redis.ClusterOptions{ DefaultUniversalOptions = &goredis.UniversalOptions{
Username: "", Username: "",
Password: "", // no password set Password: "", // no password set
MaxRetries: 2, MaxRetries: 2,
@ -29,7 +28,19 @@ var (
MinIdleConns: 10, MinIdleConns: 10,
} }
DefaultOptions = &redis.Options{ DefaultClusterOptions = &goredis.ClusterOptions{
Username: "",
Password: "", // no password set
MaxRetries: 2,
MaxRetryBackoff: 256 * time.Millisecond,
DialTimeout: 1 * time.Second,
ReadTimeout: 1 * time.Second,
WriteTimeout: 1 * time.Second,
PoolTimeout: 1 * time.Second,
MinIdleConns: 10,
}
DefaultOptions = &goredis.Options{
Username: "", Username: "",
Password: "", // no password set Password: "", // no password set
DB: 0, // use default DB DB: 0, // use default DB
@ -45,20 +56,18 @@ var (
type Store struct { type Store struct {
opts store.Options opts store.Options
cli *wrappedClient cli goredis.UniversalClient
pool pool.Pool[*strings.Builder] done chan struct{}
} pool *pool.StringsPool
type wrappedClient struct {
*redis.Client
*redis.ClusterClient
} }
func (r *Store) Connect(ctx context.Context) error { func (r *Store) Connect(ctx context.Context) error {
if r.cli.Client != nil { if r.cli == nil {
return r.cli.Client.Ping(ctx).Err() return store.ErrNotConnected
} }
return r.cli.ClusterClient.Ping(ctx).Err() err := r.cli.Ping(ctx).Err()
setSpanError(ctx, err)
return err
} }
func (r *Store) Init(opts ...store.Option) error { func (r *Store) Init(opts ...store.Option) error {
@ -66,32 +75,52 @@ func (r *Store) Init(opts ...store.Option) error {
o(&r.opts) o(&r.opts)
} }
return r.configure() err := r.configure()
if err != nil {
return err
}
return nil
} }
func (r *Store) Client() *redis.Client { func (r *Store) Client() *goredis.Client {
if r.cli.Client != nil { if c, ok := r.cli.(*goredis.Client); ok {
return r.cli.Client return c
} }
return nil return nil
} }
func (r *Store) ClusterClient() *redis.ClusterClient { func (r *Store) UniversalClient() goredis.UniversalClient {
if r.cli.ClusterClient != nil { return r.cli
return r.cli.ClusterClient }
func (r *Store) ClusterClient() *goredis.ClusterClient {
if c, ok := r.cli.(*goredis.ClusterClient); ok {
return c
} }
return nil return nil
} }
func (r *Store) Disconnect(ctx context.Context) error { func (r *Store) Disconnect(ctx context.Context) error {
if r.cli.Client != nil { var err error
return r.cli.Client.Close() select {
case <-r.done:
return err
default:
if r.cli != nil {
err = r.cli.Close()
}
close(r.done)
return err
} }
return r.cli.ClusterClient.Close()
} }
func (r *Store) Exists(ctx context.Context, key string, opts ...store.ExistsOption) error { func (r *Store) Exists(ctx context.Context, key string, opts ...store.ExistsOption) error {
b := r.pool.Get()
defer r.pool.Put(b)
options := store.NewExistsOptions(opts...) options := store.NewExistsOptions(opts...)
labels := make([]string, 0, 6)
labels = append(labels, "name", options.Name, "statement", "exists")
timeout := r.opts.Timeout timeout := r.opts.Timeout
if options.Timeout > 0 { if options.Timeout > 0 {
@ -104,31 +133,24 @@ func (r *Store) Exists(ctx context.Context, key string, opts ...store.ExistsOpti
defer cancel() defer cancel()
} }
rkey := r.getKey(r.opts.Namespace, options.Namespace, key) rkey := r.getKey(b, r.opts.Namespace, options.Namespace, key)
ctx, sp := r.opts.Tracer.Start(ctx, "cache exists "+rkey)
defer sp.Finish()
r.opts.Meter.Counter(semconv.CacheRequestInflight, "name", options.Name).Inc() r.opts.Meter.Counter(semconv.StoreRequestInflight, labels...).Inc()
ts := time.Now() ts := time.Now()
var err error val, err := r.cli.Exists(ctx, rkey).Result()
var val int64 setSpanError(ctx, err)
if r.cli.Client != nil {
val, err = r.cli.Client.Exists(ctx, rkey).Result()
} else {
val, err = r.cli.ClusterClient.Exists(ctx, rkey).Result()
}
te := time.Since(ts) te := time.Since(ts)
r.opts.Meter.Counter(semconv.CacheRequestInflight, "name", options.Name).Dec() r.opts.Meter.Counter(semconv.StoreRequestInflight, labels...).Dec()
r.opts.Meter.Summary(semconv.CacheRequestLatencyMicroseconds, "name", options.Name).Update(te.Seconds())
r.opts.Meter.Histogram(semconv.CacheRequestDurationSeconds, "name", options.Name).Update(te.Seconds()) r.opts.Meter.Summary(semconv.StoreRequestLatencyMicroseconds, labels...).Update(te.Seconds())
if err == redis.Nil || (err == nil && val == 0) { r.opts.Meter.Histogram(semconv.StoreRequestDurationSeconds, labels...).Update(te.Seconds())
r.opts.Meter.Counter(semconv.CacheRequestTotal, "name", options.Name, "status", "miss").Inc() if errors.Is(err, goredis.Nil) || (err == nil && val == 0) {
r.opts.Meter.Counter(semconv.StoreRequestTotal, append(labels, "status", "miss")...).Inc()
return store.ErrNotFound return store.ErrNotFound
} else if err == nil { } else if err == nil {
r.opts.Meter.Counter(semconv.CacheRequestTotal, "name", options.Name, "status", "hit").Inc() r.opts.Meter.Counter(semconv.StoreRequestTotal, append(labels, "status", "hit")...).Inc()
} else if err != nil { } else if err != nil {
sp.SetStatus(tracer.SpanStatusError, err.Error()) r.opts.Meter.Counter(semconv.StoreRequestTotal, append(labels, "status", "failure")...).Inc()
r.opts.Meter.Counter(semconv.CacheRequestTotal, "name", options.Name, "status", "failure").Inc()
return err return err
} }
@ -136,7 +158,12 @@ func (r *Store) Exists(ctx context.Context, key string, opts ...store.ExistsOpti
} }
func (r *Store) Read(ctx context.Context, key string, val interface{}, opts ...store.ReadOption) error { func (r *Store) Read(ctx context.Context, key string, val interface{}, opts ...store.ReadOption) error {
b := r.pool.Get()
defer r.pool.Put(b)
options := store.NewReadOptions(opts...) options := store.NewReadOptions(opts...)
labels := make([]string, 0, 6)
labels = append(labels, "name", options.Name, "statement", "read")
timeout := r.opts.Timeout timeout := r.opts.Timeout
if options.Timeout > 0 { if options.Timeout > 0 {
@ -149,31 +176,23 @@ func (r *Store) Read(ctx context.Context, key string, val interface{}, opts ...s
defer cancel() defer cancel()
} }
rkey := r.getKey(r.opts.Namespace, options.Namespace, key) rkey := r.getKey(b, r.opts.Namespace, options.Namespace, key)
ctx, sp := r.opts.Tracer.Start(ctx, "cache read "+rkey)
defer sp.Finish()
r.opts.Meter.Counter(semconv.CacheRequestInflight, "name", options.Name).Inc() r.opts.Meter.Counter(semconv.StoreRequestInflight, labels...).Inc()
ts := time.Now() ts := time.Now()
var buf []byte buf, err := r.cli.Get(ctx, rkey).Bytes()
var err error setSpanError(ctx, err)
if r.cli.Client != nil {
buf, err = r.cli.Client.Get(ctx, rkey).Bytes()
} else {
buf, err = r.cli.ClusterClient.Get(ctx, rkey).Bytes()
}
te := time.Since(ts) te := time.Since(ts)
r.opts.Meter.Counter(semconv.CacheRequestInflight, "name", options.Name).Dec() r.opts.Meter.Counter(semconv.StoreRequestInflight, labels...).Dec()
r.opts.Meter.Summary(semconv.CacheRequestLatencyMicroseconds, "name", options.Name).Update(te.Seconds()) r.opts.Meter.Summary(semconv.StoreRequestLatencyMicroseconds, labels...).Update(te.Seconds())
r.opts.Meter.Histogram(semconv.CacheRequestDurationSeconds, "name", options.Name).Update(te.Seconds()) r.opts.Meter.Histogram(semconv.StoreRequestDurationSeconds, labels...).Update(te.Seconds())
if err == redis.Nil || (err == nil && buf == nil) { if errors.Is(err, goredis.Nil) || (err == nil && buf == nil) {
r.opts.Meter.Counter(semconv.CacheRequestTotal, "name", options.Name, "status", "miss").Inc() r.opts.Meter.Counter(semconv.StoreRequestTotal, append(labels, "status", "miss")...).Inc()
return store.ErrNotFound return store.ErrNotFound
} else if err == nil { } else if err == nil {
r.opts.Meter.Counter(semconv.CacheRequestTotal, "name", options.Name, "status", "hit").Inc() r.opts.Meter.Counter(semconv.StoreRequestTotal, append(labels, "status", "hit")...).Inc()
} else if err != nil { } else if err != nil {
sp.SetStatus(tracer.SpanStatusError, err.Error()) r.opts.Meter.Counter(semconv.StoreRequestTotal, append(labels, "status", "failure")...).Inc()
r.opts.Meter.Counter(semconv.CacheRequestTotal, "name", options.Name, "status", "failure").Inc()
return err return err
} }
@ -184,7 +203,7 @@ func (r *Store) Read(ctx context.Context, key string, val interface{}, opts ...s
*b = string(buf) *b = string(buf)
default: default:
if err = r.opts.Codec.Unmarshal(buf, val); err != nil { if err = r.opts.Codec.Unmarshal(buf, val); err != nil {
sp.SetStatus(tracer.SpanStatusError, err.Error()) setSpanError(ctx, err)
} }
} }
@ -205,36 +224,42 @@ func (r *Store) MRead(ctx context.Context, keys []string, vals interface{}, opts
defer cancel() defer cancel()
} }
var rkeys []string
var pools []*strings.Builder
if r.opts.Namespace != "" || options.Namespace != "" { if r.opts.Namespace != "" || options.Namespace != "" {
rkeys = make([]string, len(keys))
pools = make([]*strings.Builder, len(keys))
for idx, key := range keys { for idx, key := range keys {
keys[idx] = r.getKey(r.opts.Namespace, options.Namespace, key) b := r.pool.Get()
pools[idx] = b
rkeys[idx] = r.getKey(b, r.opts.Namespace, options.Namespace, key)
} }
} }
ctx, sp := r.opts.Tracer.Start(ctx, fmt.Sprintf("cache mread %v", keys)) r.opts.Meter.Counter(semconv.StoreRequestInflight, "name", options.Name).Inc()
defer sp.Finish()
r.opts.Meter.Counter(semconv.CacheRequestInflight, "name", options.Name).Inc()
ts := time.Now() ts := time.Now()
var rvals []interface{} var rvals []interface{}
var err error var err error
if r.cli.Client != nil { if r.opts.Namespace != "" || options.Namespace != "" {
rvals, err = r.cli.Client.MGet(ctx, keys...).Result() rvals, err = r.cli.MGet(ctx, rkeys...).Result()
} else { for idx := range pools {
rvals, err = r.cli.ClusterClient.MGet(ctx, keys...).Result() r.pool.Put(pools[idx])
} }
} else {
rvals, err = r.cli.MGet(ctx, keys...).Result()
}
setSpanError(ctx, err)
te := time.Since(ts) te := time.Since(ts)
r.opts.Meter.Counter(semconv.CacheRequestInflight, "name", options.Name).Dec() r.opts.Meter.Counter(semconv.StoreRequestInflight, "name", options.Name).Dec()
r.opts.Meter.Summary(semconv.CacheRequestLatencyMicroseconds, "name", options.Name).Update(te.Seconds()) r.opts.Meter.Summary(semconv.StoreRequestLatencyMicroseconds, "name", options.Name).Update(te.Seconds())
r.opts.Meter.Histogram(semconv.CacheRequestDurationSeconds, "name", options.Name).Update(te.Seconds()) r.opts.Meter.Histogram(semconv.StoreRequestDurationSeconds, "name", options.Name).Update(te.Seconds())
if err == redis.Nil || (len(rvals) == 0) { if err == goredis.Nil || (len(rvals) == 0) {
r.opts.Meter.Counter(semconv.CacheRequestTotal, "name", options.Name, "status", "miss").Inc() r.opts.Meter.Counter(semconv.StoreRequestTotal, "name", options.Name, "status", "miss").Inc()
return store.ErrNotFound return store.ErrNotFound
} else if err == nil { } else if err == nil {
r.opts.Meter.Counter(semconv.CacheRequestTotal, "name", options.Name, "status", "hit").Inc() r.opts.Meter.Counter(semconv.StoreRequestTotal, "name", options.Name, "status", "hit").Inc()
} else if err != nil { } else if err != nil {
sp.SetStatus(tracer.SpanStatusError, err.Error()) r.opts.Meter.Counter(semconv.StoreRequestTotal, "name", options.Name, "status", "failure").Inc()
r.opts.Meter.Counter(semconv.CacheRequestTotal, "name", options.Name, "status", "failure").Inc()
return err return err
} }
@ -275,7 +300,7 @@ func (r *Store) MRead(ctx context.Context, keys []string, vals interface{}, opts
itm.Set(reflect.New(vt.Elem())) itm.Set(reflect.New(vt.Elem()))
if err = r.opts.Codec.Unmarshal(buf, itm.Interface()); err != nil { if err = r.opts.Codec.Unmarshal(buf, itm.Interface()); err != nil {
sp.SetStatus(tracer.SpanStatusError, err.Error()) setSpanError(ctx, err)
return err return err
} }
} }
@ -298,35 +323,41 @@ func (r *Store) MDelete(ctx context.Context, keys []string, opts ...store.Delete
defer cancel() defer cancel()
} }
var rkeys []string
var pools []*strings.Builder
if r.opts.Namespace != "" || options.Namespace != "" { if r.opts.Namespace != "" || options.Namespace != "" {
rkeys = make([]string, len(keys))
pools = make([]*strings.Builder, len(keys))
for idx, key := range keys { for idx, key := range keys {
keys[idx] = r.getKey(r.opts.Namespace, options.Namespace, key) b := r.pool.Get()
pools[idx] = b
rkeys[idx] = r.getKey(b, r.opts.Namespace, options.Namespace, key)
} }
} }
ctx, sp := r.opts.Tracer.Start(ctx, fmt.Sprintf("cache mdelete %v", keys)) r.opts.Meter.Counter(semconv.StoreRequestInflight, "name", options.Name).Inc()
defer sp.Finish()
r.opts.Meter.Counter(semconv.CacheRequestInflight, "name", options.Name).Inc()
ts := time.Now() ts := time.Now()
var err error var err error
if r.cli.Client != nil { if r.opts.Namespace != "" || options.Namespace != "" {
err = r.cli.Client.Del(ctx, keys...).Err() err = r.cli.Del(ctx, rkeys...).Err()
} else { for idx := range pools {
err = r.cli.ClusterClient.Del(ctx, keys...).Err() r.pool.Put(pools[idx])
} }
} else {
err = r.cli.Del(ctx, keys...).Err()
}
setSpanError(ctx, err)
te := time.Since(ts) te := time.Since(ts)
r.opts.Meter.Counter(semconv.CacheRequestInflight, "name", options.Name).Dec() r.opts.Meter.Counter(semconv.StoreRequestInflight, "name", options.Name).Dec()
r.opts.Meter.Summary(semconv.CacheRequestLatencyMicroseconds, "name", options.Name).Update(te.Seconds()) r.opts.Meter.Summary(semconv.StoreRequestLatencyMicroseconds, "name", options.Name).Update(te.Seconds())
r.opts.Meter.Histogram(semconv.CacheRequestDurationSeconds, "name", options.Name).Update(te.Seconds()) r.opts.Meter.Histogram(semconv.StoreRequestDurationSeconds, "name", options.Name).Update(te.Seconds())
if err == redis.Nil { if err == goredis.Nil {
r.opts.Meter.Counter(semconv.CacheRequestTotal, "name", options.Name, "status", "miss").Inc() r.opts.Meter.Counter(semconv.StoreRequestTotal, "name", options.Name, "status", "miss").Inc()
return store.ErrNotFound return store.ErrNotFound
} else if err == nil { } else if err == nil {
r.opts.Meter.Counter(semconv.CacheRequestTotal, "name", options.Name, "status", "hit").Inc() r.opts.Meter.Counter(semconv.StoreRequestTotal, "name", options.Name, "status", "hit").Inc()
} else if err != nil { } else if err != nil {
sp.SetStatus(tracer.SpanStatusError, err.Error()) r.opts.Meter.Counter(semconv.StoreRequestTotal, "name", options.Name, "status", "failure").Inc()
r.opts.Meter.Counter(semconv.CacheRequestTotal, "name", options.Name, "status", "failure").Inc()
return err return err
} }
@ -334,7 +365,12 @@ func (r *Store) MDelete(ctx context.Context, keys []string, opts ...store.Delete
} }
func (r *Store) Delete(ctx context.Context, key string, opts ...store.DeleteOption) error { func (r *Store) Delete(ctx context.Context, key string, opts ...store.DeleteOption) error {
b := r.pool.Get()
defer r.pool.Put(b)
options := store.NewDeleteOptions(opts...) options := store.NewDeleteOptions(opts...)
labels := make([]string, 0, 6)
labels = append(labels, "name", options.Name, "statement", "delete")
timeout := r.opts.Timeout timeout := r.opts.Timeout
if options.Timeout > 0 { if options.Timeout > 0 {
@ -347,29 +383,22 @@ func (r *Store) Delete(ctx context.Context, key string, opts ...store.DeleteOpti
defer cancel() defer cancel()
} }
ctx, sp := r.opts.Tracer.Start(ctx, fmt.Sprintf("cache delete %v", key)) r.opts.Meter.Counter(semconv.StoreRequestInflight, labels...).Inc()
defer sp.Finish()
r.opts.Meter.Counter(semconv.CacheRequestInflight, "name", options.Name).Inc()
ts := time.Now() ts := time.Now()
var err error err := r.cli.Del(ctx, r.getKey(b, r.opts.Namespace, options.Namespace, key)).Err()
if r.cli.Client != nil {
err = r.cli.Client.Del(ctx, r.getKey(r.opts.Namespace, options.Namespace, key)).Err()
} else {
err = r.cli.ClusterClient.Del(ctx, r.getKey(r.opts.Namespace, options.Namespace, key)).Err()
}
te := time.Since(ts) te := time.Since(ts)
r.opts.Meter.Counter(semconv.CacheRequestInflight, "name", options.Name).Dec() setSpanError(ctx, err)
r.opts.Meter.Summary(semconv.CacheRequestLatencyMicroseconds, "name", options.Name).Update(te.Seconds())
r.opts.Meter.Histogram(semconv.CacheRequestDurationSeconds, "name", options.Name).Update(te.Seconds()) r.opts.Meter.Counter(semconv.StoreRequestInflight, labels...).Dec()
if err == redis.Nil { r.opts.Meter.Summary(semconv.StoreRequestLatencyMicroseconds, labels...).Update(te.Seconds())
r.opts.Meter.Counter(semconv.CacheRequestTotal, "name", options.Name, "status", "miss").Inc() r.opts.Meter.Histogram(semconv.StoreRequestDurationSeconds, labels...).Update(te.Seconds())
if errors.Is(err, goredis.Nil) {
r.opts.Meter.Counter(semconv.StoreRequestTotal, append(labels, "status", "miss")...).Inc()
return store.ErrNotFound return store.ErrNotFound
} else if err == nil { } else if err == nil {
r.opts.Meter.Counter(semconv.CacheRequestTotal, "name", options.Name, "status", "hit").Inc() r.opts.Meter.Counter(semconv.StoreRequestTotal, append(labels, "status", "hit")...).Inc()
} else if err != nil { } else if err != nil {
sp.SetStatus(tracer.SpanStatusError, err.Error()) r.opts.Meter.Counter(semconv.StoreRequestTotal, append(labels, "status", "failure")...).Inc()
r.opts.Meter.Counter(semconv.CacheRequestTotal, "name", options.Name, "status", "failure").Inc()
return err return err
} }
@ -390,13 +419,12 @@ func (r *Store) MWrite(ctx context.Context, keys []string, vals []interface{}, o
defer cancel() defer cancel()
} }
ctx, sp := r.opts.Tracer.Start(ctx, fmt.Sprintf("cache mwrite %v", keys))
defer sp.Finish()
kvs := make([]string, 0, len(keys)*2) kvs := make([]string, 0, len(keys)*2)
pools := make([]*strings.Builder, len(keys))
for idx, key := range keys { for idx, key := range keys {
kvs = append(kvs, r.getKey(r.opts.Namespace, options.Namespace, key)) b := r.pool.Get()
pools[idx] = b
kvs = append(kvs, r.getKey(b, r.opts.Namespace, options.Namespace, key))
switch vt := vals[idx].(type) { switch vt := vals[idx].(type) {
case string: case string:
@ -406,57 +434,53 @@ func (r *Store) MWrite(ctx context.Context, keys []string, vals []interface{}, o
default: default:
buf, err := r.opts.Codec.Marshal(vt) buf, err := r.opts.Codec.Marshal(vt)
if err != nil { if err != nil {
sp.SetStatus(tracer.SpanStatusError, err.Error())
return err return err
} }
kvs = append(kvs, string(buf)) kvs = append(kvs, string(buf))
} }
} }
r.opts.Meter.Counter(semconv.CacheRequestInflight, "name", options.Name).Inc() r.opts.Meter.Counter(semconv.StoreRequestInflight, "name", options.Name).Inc()
ts := time.Now()
pipeliner := func(pipe redis.Pipeliner) error { pipeliner := func(pipe goredis.Pipeliner) error {
for idx := 0; idx < len(kvs); idx += 2 { for idx := 0; idx < len(kvs); idx += 2 {
if _, err := pipe.Set(ctx, kvs[idx], kvs[idx+1], options.TTL).Result(); err != nil { if _, err := pipe.Set(ctx, kvs[idx], kvs[idx+1], options.TTL).Result(); err != nil {
setSpanError(ctx, err)
return err return err
} }
} }
return nil return nil
} }
var err error ts := time.Now()
var cmds []redis.Cmder cmds, err := r.cli.Pipelined(ctx, pipeliner)
for idx := range pools {
if r.cli.Client != nil { r.pool.Put(pools[idx])
cmds, err = r.cli.Client.Pipelined(ctx, pipeliner)
} else {
cmds, err = r.cli.ClusterClient.Pipelined(ctx, pipeliner)
} }
te := time.Since(ts) te := time.Since(ts)
r.opts.Meter.Counter(semconv.CacheRequestInflight, "name", options.Name).Dec() setSpanError(ctx, err)
r.opts.Meter.Summary(semconv.CacheRequestLatencyMicroseconds, "name", options.Name).Update(te.Seconds())
r.opts.Meter.Histogram(semconv.CacheRequestDurationSeconds, "name", options.Name).Update(te.Seconds()) r.opts.Meter.Counter(semconv.StoreRequestInflight, "name", options.Name).Dec()
if err == redis.Nil { r.opts.Meter.Summary(semconv.StoreRequestLatencyMicroseconds, "name", options.Name).Update(te.Seconds())
r.opts.Meter.Counter(semconv.CacheRequestTotal, "name", options.Name, "status", "miss").Inc() r.opts.Meter.Histogram(semconv.StoreRequestDurationSeconds, "name", options.Name).Update(te.Seconds())
if err == goredis.Nil {
r.opts.Meter.Counter(semconv.StoreRequestTotal, "name", options.Name, "status", "miss").Inc()
return store.ErrNotFound return store.ErrNotFound
} else if err == nil { } else if err == nil {
r.opts.Meter.Counter(semconv.CacheRequestTotal, "name", options.Name, "status", "hit").Inc() r.opts.Meter.Counter(semconv.StoreRequestTotal, "name", options.Name, "status", "hit").Inc()
} else if err != nil { } else if err != nil {
sp.SetStatus(tracer.SpanStatusError, err.Error()) r.opts.Meter.Counter(semconv.StoreRequestTotal, "name", options.Name, "status", "failure").Inc()
r.opts.Meter.Counter(semconv.CacheRequestTotal, "name", options.Name, "status", "failure").Inc()
return err return err
} }
for _, cmd := range cmds { for _, cmd := range cmds {
if err = cmd.Err(); err != nil { if err = cmd.Err(); err != nil {
if err == redis.Nil { if err == goredis.Nil {
r.opts.Meter.Counter(semconv.CacheRequestTotal, "name", options.Name, "status", "miss").Inc() r.opts.Meter.Counter(semconv.StoreRequestTotal, "name", options.Name, "status", "miss").Inc()
return store.ErrNotFound return store.ErrNotFound
} }
sp.SetStatus(tracer.SpanStatusError, err.Error()) setSpanError(ctx, err)
r.opts.Meter.Counter(semconv.CacheRequestTotal, "name", options.Name, "status", "failure").Inc() r.opts.Meter.Counter(semconv.StoreRequestTotal, "name", options.Name, "status", "failure").Inc()
return err return err
} }
} }
@ -465,7 +489,12 @@ func (r *Store) MWrite(ctx context.Context, keys []string, vals []interface{}, o
} }
func (r *Store) Write(ctx context.Context, key string, val interface{}, opts ...store.WriteOption) error { func (r *Store) Write(ctx context.Context, key string, val interface{}, opts ...store.WriteOption) error {
b := r.pool.Get()
defer r.pool.Put(b)
options := store.NewWriteOptions(opts...) options := store.NewWriteOptions(opts...)
labels := make([]string, 0, 6)
labels = append(labels, "name", options.Name, "statement", "write")
timeout := r.opts.Timeout timeout := r.opts.Timeout
if options.Timeout > 0 { if options.Timeout > 0 {
@ -478,9 +507,7 @@ func (r *Store) Write(ctx context.Context, key string, val interface{}, opts ...
defer cancel() defer cancel()
} }
rkey := r.getKey(r.opts.Namespace, options.Namespace, key) rkey := r.getKey(b, r.opts.Namespace, options.Namespace, key)
ctx, sp := r.opts.Tracer.Start(ctx, fmt.Sprintf("cache write %v", rkey))
defer sp.Finish()
var buf []byte var buf []byte
switch vt := val.(type) { switch vt := val.(type) {
@ -492,31 +519,26 @@ func (r *Store) Write(ctx context.Context, key string, val interface{}, opts ...
var err error var err error
buf, err = r.opts.Codec.Marshal(val) buf, err = r.opts.Codec.Marshal(val)
if err != nil { if err != nil {
sp.SetStatus(tracer.SpanStatusError, err.Error())
return err return err
} }
} }
r.opts.Meter.Counter(semconv.CacheRequestInflight, "name", options.Name).Inc() r.opts.Meter.Counter(semconv.StoreRequestInflight, labels...).Inc()
ts := time.Now() ts := time.Now()
var err error err := r.cli.Set(ctx, rkey, buf, options.TTL).Err()
if r.cli.Client != nil {
err = r.cli.Client.Set(ctx, rkey, buf, options.TTL).Err()
} else {
err = r.cli.ClusterClient.Set(ctx, rkey, buf, options.TTL).Err()
}
te := time.Since(ts) te := time.Since(ts)
r.opts.Meter.Counter(semconv.CacheRequestInflight, "name", options.Name).Dec() setSpanError(ctx, err)
r.opts.Meter.Summary(semconv.CacheRequestLatencyMicroseconds, "name", options.Name).Update(te.Seconds())
r.opts.Meter.Histogram(semconv.CacheRequestDurationSeconds, "name", options.Name).Update(te.Seconds()) r.opts.Meter.Counter(semconv.StoreRequestInflight, labels...).Dec()
if err == redis.Nil { r.opts.Meter.Summary(semconv.StoreRequestLatencyMicroseconds, labels...).Update(te.Seconds())
r.opts.Meter.Counter(semconv.CacheRequestTotal, "name", options.Name, "status", "miss").Inc() r.opts.Meter.Histogram(semconv.StoreRequestDurationSeconds, labels...).Update(te.Seconds())
if errors.Is(err, goredis.Nil) {
r.opts.Meter.Counter(semconv.StoreRequestTotal, append(labels, "status", "miss")...).Inc()
return store.ErrNotFound return store.ErrNotFound
} else if err == nil { } else if err == nil {
r.opts.Meter.Counter(semconv.CacheRequestTotal, "name", options.Name, "status", "hit").Inc() r.opts.Meter.Counter(semconv.StoreRequestTotal, append(labels, "status", "hit")...).Inc()
} else if err != nil { } else if err != nil {
sp.SetStatus(tracer.SpanStatusError, err.Error()) r.opts.Meter.Counter(semconv.StoreRequestTotal, append(labels, "status", "failure")...).Inc()
r.opts.Meter.Counter(semconv.CacheRequestTotal, "name", options.Name, "status", "failure").Inc()
return err return err
} }
@ -524,12 +546,15 @@ func (r *Store) Write(ctx context.Context, key string, val interface{}, opts ...
} }
func (r *Store) List(ctx context.Context, opts ...store.ListOption) ([]string, error) { func (r *Store) List(ctx context.Context, opts ...store.ListOption) ([]string, error) {
b := r.pool.Get()
defer r.pool.Put(b)
options := store.NewListOptions(opts...) options := store.NewListOptions(opts...)
if len(options.Namespace) == 0 { if len(options.Namespace) == 0 {
options.Namespace = r.opts.Namespace options.Namespace = r.opts.Namespace
} }
rkey := r.getKey(options.Namespace, "", options.Prefix+"*") rkey := r.getKey(b, options.Namespace, "", options.Prefix+"*")
if options.Suffix != "" { if options.Suffix != "" {
rkey += options.Suffix rkey += options.Suffix
} }
@ -545,19 +570,14 @@ func (r *Store) List(ctx context.Context, opts ...store.ListOption) ([]string, e
defer cancel() defer cancel()
} }
ctx, sp := r.opts.Tracer.Start(ctx, fmt.Sprintf("cache list %v", rkey))
defer sp.Finish()
// TODO: add support for prefix/suffix/limit // TODO: add support for prefix/suffix/limit
r.opts.Meter.Counter(semconv.CacheRequestInflight, "name", options.Name).Inc() r.opts.Meter.Counter(semconv.StoreRequestInflight, "name", options.Name).Inc()
ts := time.Now() ts := time.Now()
var keys []string var keys []string
var err error var err error
if r.cli.Client != nil { if c, ok := r.cli.(*goredis.ClusterClient); ok {
keys, err = r.cli.Client.Keys(ctx, rkey).Result() err = c.ForEachMaster(ctx, func(nctx context.Context, cli *goredis.Client) error {
} else {
err = r.cli.ClusterClient.ForEachMaster(ctx, func(nctx context.Context, cli *redis.Client) error {
nkeys, nerr := cli.Keys(nctx, rkey).Result() nkeys, nerr := cli.Keys(nctx, rkey).Result()
if nerr != nil { if nerr != nil {
return nerr return nerr
@ -565,19 +585,22 @@ func (r *Store) List(ctx context.Context, opts ...store.ListOption) ([]string, e
keys = append(keys, nkeys...) keys = append(keys, nkeys...)
return nil return nil
}) })
} else {
keys, err = r.cli.Keys(ctx, rkey).Result()
} }
te := time.Since(ts) te := time.Since(ts)
r.opts.Meter.Counter(semconv.CacheRequestInflight, "name", options.Name).Dec() setSpanError(ctx, err)
r.opts.Meter.Summary(semconv.CacheRequestLatencyMicroseconds, "name", options.Name).Update(te.Seconds())
r.opts.Meter.Histogram(semconv.CacheRequestDurationSeconds, "name", options.Name).Update(te.Seconds()) r.opts.Meter.Counter(semconv.StoreRequestInflight, "name", options.Name).Dec()
if err == redis.Nil { r.opts.Meter.Summary(semconv.StoreRequestLatencyMicroseconds, "name", options.Name).Update(te.Seconds())
r.opts.Meter.Counter(semconv.CacheRequestTotal, "name", options.Name, "status", "miss").Inc() r.opts.Meter.Histogram(semconv.StoreRequestDurationSeconds, "name", options.Name).Update(te.Seconds())
if err == goredis.Nil {
r.opts.Meter.Counter(semconv.StoreRequestTotal, "name", options.Name, "status", "miss").Inc()
return nil, store.ErrNotFound return nil, store.ErrNotFound
} else if err == nil { } else if err == nil {
r.opts.Meter.Counter(semconv.CacheRequestTotal, "name", options.Name, "status", "hit").Inc() r.opts.Meter.Counter(semconv.StoreRequestTotal, "name", options.Name, "status", "hit").Inc()
} else if err != nil { } else if err != nil {
sp.SetStatus(tracer.SpanStatusError, err.Error()) r.opts.Meter.Counter(semconv.StoreRequestTotal, "name", options.Name, "status", "failure").Inc()
r.opts.Meter.Counter(semconv.CacheRequestTotal, "name", options.Name, "status", "failure").Inc()
return nil, err return nil, err
} }
@ -609,76 +632,106 @@ func (r *Store) String() string {
} }
func NewStore(opts ...store.Option) *Store { func NewStore(opts ...store.Option) *Store {
return &Store{opts: store.NewOptions(opts...)} return &Store{done: make(chan struct{}), opts: store.NewOptions(opts...)}
} }
func (r *Store) configure() error { func (r *Store) configure() error {
var redisOptions *redis.Options
var redisClusterOptions *redis.ClusterOptions
var err error
nodes := r.opts.Addrs
if len(nodes) == 0 {
nodes = []string{"redis://127.0.0.1:6379"}
}
if r.cli != nil && r.opts.Context == nil { if r.cli != nil && r.opts.Context == nil {
return nil return nil
} }
universalOptions := DefaultUniversalOptions
if r.opts.Context != nil { if r.opts.Context != nil {
if c, ok := r.opts.Context.Value(configKey{}).(*redis.Options); ok { if o, ok := r.opts.Context.Value(configKey{}).(*goredis.Options); ok {
redisOptions = c universalOptions.Addrs = []string{o.Addr}
universalOptions.Dialer = o.Dialer
universalOptions.OnConnect = o.OnConnect
universalOptions.Username = o.Username
universalOptions.Password = o.Password
universalOptions.MaxRetries = o.MaxRetries
universalOptions.MinRetryBackoff = o.MinRetryBackoff
universalOptions.MaxRetryBackoff = o.MaxRetryBackoff
universalOptions.DialTimeout = o.DialTimeout
universalOptions.ReadTimeout = o.ReadTimeout
universalOptions.WriteTimeout = o.WriteTimeout
universalOptions.ContextTimeoutEnabled = o.ContextTimeoutEnabled
universalOptions.PoolFIFO = o.PoolFIFO
universalOptions.PoolSize = o.PoolSize
universalOptions.PoolTimeout = o.PoolTimeout
universalOptions.MinIdleConns = o.MinIdleConns
universalOptions.MaxIdleConns = o.MaxIdleConns
universalOptions.ConnMaxIdleTime = o.ConnMaxIdleTime
universalOptions.ConnMaxLifetime = o.ConnMaxLifetime
if r.opts.TLSConfig != nil { if r.opts.TLSConfig != nil {
redisOptions.TLSConfig = r.opts.TLSConfig universalOptions.TLSConfig = r.opts.TLSConfig
} }
} }
if c, ok := r.opts.Context.Value(clusterConfigKey{}).(*redis.ClusterOptions); ok { if o, ok := r.opts.Context.Value(clusterConfigKey{}).(*goredis.ClusterOptions); ok {
redisClusterOptions = c universalOptions.Addrs = o.Addrs
universalOptions.Dialer = o.Dialer
universalOptions.OnConnect = o.OnConnect
universalOptions.Username = o.Username
universalOptions.Password = o.Password
universalOptions.MaxRedirects = o.MaxRedirects
universalOptions.ReadOnly = o.ReadOnly
universalOptions.RouteByLatency = o.RouteByLatency
universalOptions.RouteRandomly = o.RouteRandomly
universalOptions.MaxRetries = o.MaxRetries
universalOptions.MinRetryBackoff = o.MinRetryBackoff
universalOptions.MaxRetryBackoff = o.MaxRetryBackoff
universalOptions.DialTimeout = o.DialTimeout
universalOptions.ReadTimeout = o.ReadTimeout
universalOptions.WriteTimeout = o.WriteTimeout
universalOptions.ContextTimeoutEnabled = o.ContextTimeoutEnabled
universalOptions.PoolFIFO = o.PoolFIFO
universalOptions.PoolSize = o.PoolSize
universalOptions.PoolTimeout = o.PoolTimeout
universalOptions.MinIdleConns = o.MinIdleConns
universalOptions.MaxIdleConns = o.MaxIdleConns
universalOptions.ConnMaxIdleTime = o.ConnMaxIdleTime
universalOptions.ConnMaxLifetime = o.ConnMaxLifetime
if r.opts.TLSConfig != nil { if r.opts.TLSConfig != nil {
redisClusterOptions.TLSConfig = r.opts.TLSConfig universalOptions.TLSConfig = r.opts.TLSConfig
}
}
if o, ok := r.opts.Context.Value(universalConfigKey{}).(*goredis.UniversalOptions); ok {
universalOptions = o
if r.opts.TLSConfig != nil {
universalOptions.TLSConfig = r.opts.TLSConfig
} }
} }
} }
if redisOptions != nil && redisClusterOptions != nil { if len(r.opts.Addrs) > 0 {
return fmt.Errorf("must specify only one option Config or ClusterConfig") universalOptions.Addrs = r.opts.Addrs
} else {
universalOptions.Addrs = []string{"127.0.0.1:6379"}
} }
if redisOptions == nil && redisClusterOptions == nil && r.cli != nil { r.cli = goredis.NewUniversalClient(universalOptions)
return nil setTracing(r.cli, r.opts.Tracer)
}
if redisOptions == nil && redisClusterOptions == nil && len(nodes) == 1 { r.pool = pool.NewStringsPool(50)
redisOptions, err = redis.ParseURL(nodes[0])
if err != nil {
redisOptions = DefaultOptions
redisOptions.Addr = r.opts.Addrs[0]
redisOptions.TLSConfig = r.opts.TLSConfig
}
} else if redisOptions == nil && redisClusterOptions == nil && len(nodes) > 1 {
redisClusterOptions = DefaultClusterOptions
redisClusterOptions.Addrs = r.opts.Addrs
redisClusterOptions.TLSConfig = r.opts.TLSConfig
}
if redisOptions != nil { r.statsMeter()
r.cli = &wrappedClient{Client: redis.NewClient(redisOptions)}
} else if redisClusterOptions != nil {
r.cli = &wrappedClient{ClusterClient: redis.NewClusterClient(redisClusterOptions)}
}
r.pool = pool.NewPool(func() *strings.Builder { return &strings.Builder{} })
return nil return nil
} }
func (r *Store) getKey(mainNamespace string, opNamespace string, key string) string { func (r *Store) getKey(b *strings.Builder, mainNamespace string, opNamespace string, key string) string {
b := r.pool.Get()
defer r.pool.Put(b)
b.Reset()
if opNamespace == "" { if opNamespace == "" {
opNamespace = mainNamespace opNamespace = mainNamespace
} }

View File

@ -7,13 +7,62 @@ import (
"testing" "testing"
"time" "time"
goredis "github.com/redis/go-redis/v9"
"go.unistack.org/micro/v3/store" "go.unistack.org/micro/v3/store"
"go.unistack.org/micro/v3/tracer"
) )
func TestLazyConnect(t *testing.T) {
ctx := context.Background()
var err error
r := NewStore()
if err = r.Init(); err != nil {
t.Fatal(err)
}
if err = r.Connect(ctx); err != nil {
t.Logf("connect failed %v", err)
}
for {
if err = r.Write(ctx, "mykey", "myval"); err != nil {
t.Logf("failed to write %v", err)
}
}
}
func TestKeepTTL(t *testing.T) {
ctx := context.Background()
if tr := os.Getenv("INTEGRATION_TESTS"); len(tr) > 0 {
t.Skip()
}
r := NewStore(store.Addrs(os.Getenv("STORE_NODES")))
if err := r.Init(); err != nil {
t.Fatal(err)
}
if err := r.Connect(ctx); err != nil {
t.Fatal(err)
}
key := "key"
err := r.Write(ctx, key, "val1", store.WriteTTL(15*time.Second))
if err != nil {
t.Fatalf("Write error: %v", err)
}
time.Sleep(3 * time.Second)
err = r.Write(ctx, key, "val2", store.WriteTTL(-1))
if err != nil {
t.Fatalf("Write error: %v", err)
}
}
func Test_rkv_configure(t *testing.T) { func Test_rkv_configure(t *testing.T) {
type fields struct { type fields struct {
options store.Options options store.Options
Client *wrappedClient Client goredis.UniversalClient
} }
type wantValues struct { type wantValues struct {
username string username string
@ -36,7 +85,7 @@ func Test_rkv_configure(t *testing.T) {
}, },
}, },
{ {
name: "legacy Url", fields: fields{options: store.Options{Addrs: []string{"127.0.0.1:6379"}}, Client: nil}, name: "legacy Url", fields: fields{options: store.Options{Tracer: tracer.DefaultTracer, Addrs: []string{"127.0.0.1:6379"}}, Client: nil},
wantErr: false, want: wantValues{ wantErr: false, want: wantValues{
username: "", username: "",
password: "", password: "",
@ -44,7 +93,7 @@ func Test_rkv_configure(t *testing.T) {
}, },
}, },
{ {
name: "New Url", fields: fields{options: store.Options{Addrs: []string{"redis://127.0.0.1:6379"}}, Client: nil}, name: "New Url", fields: fields{options: store.Options{Tracer: tracer.DefaultTracer, Addrs: []string{"redis://127.0.0.1:6379"}}, Client: nil},
wantErr: false, want: wantValues{ wantErr: false, want: wantValues{
username: "", username: "",
password: "", password: "",
@ -52,7 +101,7 @@ func Test_rkv_configure(t *testing.T) {
}, },
}, },
{ {
name: "Url with Pwd", fields: fields{options: store.Options{Addrs: []string{"redis://:password@redis:6379"}}, Client: nil}, name: "Url with Pwd", fields: fields{options: store.Options{Tracer: tracer.DefaultTracer, Addrs: []string{"redis://:password@redis:6379"}}, Client: nil},
wantErr: false, want: wantValues{ wantErr: false, want: wantValues{
username: "", username: "",
password: "password", password: "password",
@ -60,7 +109,7 @@ func Test_rkv_configure(t *testing.T) {
}, },
}, },
{ {
name: "Url with username and Pwd", fields: fields{options: store.Options{Addrs: []string{"redis://username:password@redis:6379"}}, Client: nil}, name: "Url with username and Pwd", fields: fields{options: store.Options{Tracer: tracer.DefaultTracer, Addrs: []string{"redis://username:password@redis:6379"}}, Client: nil},
wantErr: false, want: wantValues{ wantErr: false, want: wantValues{
username: "username", username: "username",
password: "password", password: "password",

49
stats.go Normal file
View File

@ -0,0 +1,49 @@
package redis
import (
"time"
goredis "github.com/redis/go-redis/v9"
"go.unistack.org/micro/v3/meter"
)
var (
PoolHitsTotal = "pool_hits_total"
PoolMissesTotal = "pool_misses_total"
PoolTimeoutTotal = "pool_timeout_total"
PoolConnTotalCurrent = "pool_conn_total_current"
PoolConnIdleCurrent = "pool_conn_idle_current"
PoolConnStaleTotal = "pool_conn_stale_total"
)
type Statser interface {
PoolStats() *goredis.PoolStats
}
func (r *Store) statsMeter() {
var st Statser
if r.cli != nil {
st = r.cli
} else {
return
}
go func() {
ticker := time.NewTicker(meter.DefaultMeterStatsInterval)
defer ticker.Stop()
for _ = range ticker.C {
if st == nil {
return
}
stats := st.PoolStats()
r.opts.Meter.Counter(PoolHitsTotal).Set(uint64(stats.Hits))
r.opts.Meter.Counter(PoolMissesTotal).Set(uint64(stats.Misses))
r.opts.Meter.Counter(PoolTimeoutTotal).Set(uint64(stats.Timeouts))
r.opts.Meter.Counter(PoolConnTotalCurrent).Set(uint64(stats.TotalConns))
r.opts.Meter.Counter(PoolConnIdleCurrent).Set(uint64(stats.IdleConns))
r.opts.Meter.Counter(PoolConnStaleTotal).Set(uint64(stats.StaleConns))
}
}()
}

128
tracer.go Normal file
View File

@ -0,0 +1,128 @@
package redis
import (
"context"
"fmt"
"net"
"strconv"
rediscmd "github.com/redis/go-redis/extra/rediscmd/v9"
goredis "github.com/redis/go-redis/v9"
"go.unistack.org/micro/v3/tracer"
)
func setTracing(rdb goredis.UniversalClient, tr tracer.Tracer, opts ...tracer.SpanOption) {
switch rdb := rdb.(type) {
case *goredis.Client:
opt := rdb.Options()
connString := formatDBConnString(opt.Network, opt.Addr)
rdb.AddHook(newTracingHook(connString, tr))
case *goredis.ClusterClient:
rdb.OnNewNode(func(rdb *goredis.Client) {
opt := rdb.Options()
connString := formatDBConnString(opt.Network, opt.Addr)
rdb.AddHook(newTracingHook(connString, tr))
})
case *goredis.Ring:
rdb.OnNewNode(func(rdb *goredis.Client) {
opt := rdb.Options()
connString := formatDBConnString(opt.Network, opt.Addr)
rdb.AddHook(newTracingHook(connString, tr))
})
}
}
type tracingHook struct {
tr tracer.Tracer
opts []tracer.SpanOption
}
var _ goredis.Hook = (*tracingHook)(nil)
func newTracingHook(connString string, tr tracer.Tracer, opts ...tracer.SpanOption) *tracingHook {
opts = append(opts, tracer.WithSpanKind(tracer.SpanKindClient))
if connString != "" {
opts = append(opts, tracer.WithSpanLabels("db.connection_string", connString))
}
return &tracingHook{
tr: tr,
opts: opts,
}
}
func (h *tracingHook) DialHook(hook goredis.DialHook) goredis.DialHook {
return func(ctx context.Context, network, addr string) (net.Conn, error) {
/*
_, span := h.tr.Start(ctx, "goredis.dial", h.opts...)
defer span.Finish()
*/
conn, err := hook(ctx, network, addr)
// recordError(span, err)
return conn, err
}
}
func (h *tracingHook) ProcessHook(hook goredis.ProcessHook) goredis.ProcessHook {
return func(ctx context.Context, cmd goredis.Cmder) error {
cmdString := rediscmd.CmdString(cmd)
var err error
switch cmdString {
case "cluster slots":
break
default:
_, span := h.tr.Start(ctx, "sdk.database", append(h.opts, tracer.WithSpanLabels("db.statement", cmdString))...)
defer func() {
recordError(span, err)
span.Finish()
}()
}
err = hook(ctx, cmd)
return err
}
}
func (h *tracingHook) ProcessPipelineHook(hook goredis.ProcessPipelineHook) goredis.ProcessPipelineHook {
return func(ctx context.Context, cmds []goredis.Cmder) error {
_, cmdsString := rediscmd.CmdsString(cmds)
opts := append(h.opts, tracer.WithSpanLabels(
"db.database.num_cmd", strconv.Itoa(len(cmds)),
"db.statement", cmdsString,
))
_, span := h.tr.Start(ctx, "sdk.database", opts...)
defer span.Finish()
err := hook(ctx, cmds)
recordError(span, err)
return err
}
}
func setSpanError(ctx context.Context, err error) {
if err == nil || err == goredis.Nil {
return
}
if sp, ok := tracer.SpanFromContext(ctx); !ok && sp != nil {
sp.SetStatus(tracer.SpanStatusError, err.Error())
}
}
func recordError(span tracer.Span, err error) {
if err != nil && err != goredis.Nil {
span.SetStatus(tracer.SpanStatusError, err.Error())
}
}
func formatDBConnString(network, addr string) string {
if network == "tcp" {
network = "redis"
}
return fmt.Sprintf("%s://%s", network, addr)
}