Compare commits

..

9 Commits
v3 ... master

Author SHA1 Message Date
512531e797 Merge pull request 'Update workflows' (#127) from atolstikhin/micro-store-redis:master into master
Some checks failed
test / test (push) Failing after 44s
Reviewed-on: #127
2024-12-15 23:09:54 +03:00
54cb7188b8 Merge branch 'master' into master
Some checks failed
automerge / automerge (pull_request) Failing after 15s
autoapprove / autoapprove (pull_request) Failing after 2m0s
lint / lint (pull_request) Successful in 4m52s
dependabot-automerge / automerge (pull_request) Failing after 14m56s
test / test (pull_request) Successful in 17m34s
2024-12-15 22:10:20 +03:00
21d40b8e69 fixup lint
Some checks failed
build / lint (push) Successful in 29s
build / test (push) Failing after 37s
codeql / analyze (go) (push) Failing after 7m23s
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2024-12-15 22:09:59 +03:00
Aleksandr Tolstikhin
b61b8081b7 Update workflows
Some checks failed
automerge / automerge (pull_request) Has been skipped
dependabot-automerge / automerge (pull_request) Has been skipped
lint / lint (pull_request) Failing after 51s
test / test (pull_request) Failing after 10m53s
autoapprove / autoapprove (pull_request) Failing after 10m47s
2024-12-14 01:52:20 +07:00
c8d21b4ef4 Replace RedisCluster to RedisUniversalClient (#114)
Some checks failed
build / test (push) Failing after 12s
build / lint (push) Failing after 15s
codeql / analyze (go) (push) Failing after 14m50s
1. Replace redis.Client to redis.UniversalClient
2. Replace ClusterConfig to UniversalConfig

closes #113

Co-authored-by: Aleksandr Tolstikhin <atolstikhin@mtsbank.ru>
Co-authored-by: Vasiliy Tolstov <v.tolstov@unistack.org>
Reviewed-on: #114
Reviewed-by: Василий Толстов <v.tolstov@unistack.org>
Co-authored-by: Александр Толстихин <tolstihin1996@mail.ru>
Co-committed-by: Александр Толстихин <tolstihin1996@mail.ru>
2024-10-04 00:20:23 +03:00
195c604a31 Merge pull request 'add ability to get *redis.Client' (#111) from redis into master
Some checks failed
build / test (push) Failing after 1m28s
build / lint (push) Failing after 2m34s
codeql / analyze (go) (push) Failing after 2m44s
Reviewed-on: #111
2023-12-12 13:53:00 +03:00
b263b69031 add ability to get *redis.Client
Some checks failed
codeql / analyze (go) (pull_request) Failing after 2m41s
prbuild / test (pull_request) Failing after 1m29s
prbuild / lint (pull_request) Failing after 2m34s
autoapprove / autoapprove (pull_request) Failing after 1m26s
automerge / automerge (pull_request) Failing after 4s
dependabot-automerge / automerge (pull_request) Has been skipped
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2023-12-12 13:52:37 +03:00
4459bfa1a0 Merge pull request 'add mwrite func' (#109) from mwrite into master
Reviewed-on: #109
2023-10-21 00:58:08 +03:00
b90361e48a add MWrite func
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2023-10-21 00:57:12 +03:00
9 changed files with 202 additions and 1072 deletions

1
.gitignore vendored
View File

@ -1 +0,0 @@
.idea

View File

@ -1,86 +0,0 @@
package redis
import (
"context"
"errors"
"net"
"time"
goredis "github.com/redis/go-redis/v9"
"go.unistack.org/micro/v3/store"
)
type eventHook struct {
s *Store
}
var _ goredis.Hook = (*eventHook)(nil)
func newEventHook(s *Store) *eventHook {
return &eventHook{s: s}
}
func (h *eventHook) DialHook(hook goredis.DialHook) goredis.DialHook {
return func(ctx context.Context, network, addr string) (net.Conn, error) {
conn, err := hook(ctx, network, addr)
if err != nil {
if !isRedisError(err) {
if h.s.connected.CompareAndSwap(1, 0) {
h.s.sendEvent(&event{ts: time.Now(), err: err, t: store.EventTypeDisconnect})
}
} else {
h.s.connected.Store(1)
}
} else {
if h.s.connected.CompareAndSwap(0, 1) {
h.s.sendEvent(&event{ts: time.Now(), err: err, t: store.EventTypeConnect})
}
}
return conn, err
}
}
func (h *eventHook) ProcessHook(hook goredis.ProcessHook) goredis.ProcessHook {
return func(ctx context.Context, cmd goredis.Cmder) error {
err := hook(ctx, cmd)
if err != nil {
if !isRedisError(err) {
if h.s.connected.CompareAndSwap(1, 0) {
h.s.sendEvent(&event{ts: time.Now(), err: err, t: store.EventTypeDisconnect})
}
} else {
h.s.connected.Store(1)
}
} else {
if h.s.connected.CompareAndSwap(0, 1) {
h.s.sendEvent(&event{ts: time.Now(), err: err, t: store.EventTypeConnect})
}
}
return err
}
}
func (h *eventHook) ProcessPipelineHook(hook goredis.ProcessPipelineHook) goredis.ProcessPipelineHook {
return func(ctx context.Context, cmds []goredis.Cmder) error {
err := hook(ctx, cmds)
if err != nil {
if !isRedisError(err) {
if h.s.connected.CompareAndSwap(1, 0) {
h.s.sendEvent(&event{ts: time.Now(), err: err, t: store.EventTypeDisconnect})
}
} else {
h.s.connected.Store(1)
}
} else {
if h.s.connected.CompareAndSwap(0, 1) {
h.s.sendEvent(&event{ts: time.Now(), err: err, t: store.EventTypeConnect})
}
}
return err
}
}
func isRedisError(err error) bool {
var rerr goredis.Error
return errors.As(err, &rerr)
}

17
go.mod
View File

@ -1,19 +1,14 @@
module go.unistack.org/micro-store-redis/v3 module go.unistack.org/micro-store-redis/v4
go 1.22 go 1.20
toolchain go1.22.4
require ( require (
github.com/redis/go-redis/extra/rediscmd/v9 v9.7.0 github.com/redis/go-redis/v9 v9.2.1
github.com/redis/go-redis/v9 v9.7.0 go.unistack.org/micro/v4 v4.0.7
go.unistack.org/micro/v3 v3.10.108
) )
require ( require (
github.com/cespare/xxhash/v2 v2.3.0 // indirect github.com/cespare/xxhash/v2 v2.2.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/google/go-cmp v0.6.0 // indirect github.com/patrickmn/go-cache v2.1.0+incompatible // indirect
go.unistack.org/micro-proto/v3 v3.4.1 // indirect
google.golang.org/protobuf v1.35.2 // indirect
) )

24
go.sum
View File

@ -1,20 +1,12 @@
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/bsm/gomega v1.27.10/go.mod h1:JyEr/xRbxbtgWNi8tIEVPUYZ5Dzef52k01W3YH0H+O0= github.com/cespare/xxhash/v2 v2.2.0 h1:DC2CZ1Ep5Y4k3ZQ899DldepgrayRUGE6BBZ/cd9Cj44=
github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs= github.com/cespare/xxhash/v2 v2.2.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=
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/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI= github.com/patrickmn/go-cache v2.1.0+incompatible h1:HRMgzkcYKYpi3C8ajMPV8OFXaaRUnok+kx1WdO15EQc=
github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY= github.com/patrickmn/go-cache v2.1.0+incompatible/go.mod h1:3Qf8kWWT7OJRJbdiICTKqZju1ZixQ/KpMGzzAfe6+WQ=
github.com/redis/go-redis/extra/rediscmd/v9 v9.7.0 h1:BIx9TNZH/Jsr4l1i7VVxnV0JPiwYj8qyrHyuL0fGZrk= github.com/redis/go-redis/v9 v9.2.1 h1:WlYJg71ODF0dVspZZCpYmoF1+U1Jjk9Rwd7pq6QmlCg=
github.com/redis/go-redis/extra/rediscmd/v9 v9.7.0/go.mod h1:eTg/YQtGYAZD5r3DlGlJptJ45AHA+/G+2NPn30PKzik= github.com/redis/go-redis/v9 v9.2.1/go.mod h1:hdY0cQFCN4fnSYT6TkisLufl/4W5UIXyv0b/CLO2V2M=
github.com/redis/go-redis/v9 v9.7.0 h1:HhLSs+B6O021gwzl+locl0zEDnyNkxMtf/Z3NNBMa9E= go.unistack.org/micro/v4 v4.0.7 h1:2lwtZlHcSwgkahhFbkI4x1lOS79lw8uLHtcEhlFF+AM=
github.com/redis/go-redis/v9 v9.7.0/go.mod h1:f6zhXITC7JUJIlPEiBOTXxJgPLdZcA93GewI7inzyWw= go.unistack.org/micro/v4 v4.0.7/go.mod h1:bVEYTlPi0EsdgZZt311bIroDg9ict7ky3C87dSCCAGk=
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.108 h1:3L7SkilMVLtH8y3pQIPtr3jjQYrf0AMv1oAkoL3nFkE=
go.unistack.org/micro/v3 v3.10.108/go.mod h1:YzMldzHN9Ei+zy5t/Psu7RUWDZwUfrNYiStSQtTz90g=
google.golang.org/protobuf v1.35.2 h1:8Ar7bF+apOIoThw1EdZl0p1oWvMqTHmpA2fRTyZO8io=
google.golang.org/protobuf v1.35.2/go.mod h1:9fA7Ob0pmnwhb644+1+CVWFRbNajQ6iRojtC/QF5bRE=

View File

@ -1,67 +1,12 @@
package redis package redis
import ( import (
goredis "github.com/redis/go-redis/v9" "github.com/redis/go-redis/v9"
"go.unistack.org/micro/v3/logger" "go.unistack.org/micro/v4/options"
"go.unistack.org/micro/v3/meter"
"go.unistack.org/micro/v3/store"
"go.unistack.org/micro/v3/tracer"
) )
type configKey struct{}
func Config(c *goredis.Options) store.Option {
return store.SetOption(configKey{}, c)
}
type clusterConfigKey struct{}
func ClusterConfig(c *goredis.ClusterOptions) store.Option {
return store.SetOption(clusterConfigKey{}, c)
}
type universalConfigKey struct{} type universalConfigKey struct{}
func UniversalConfig(c *goredis.UniversalOptions) store.Option { func UniversalConfig(c *redis.UniversalOptions) options.Option {
return store.SetOption(universalConfigKey{}, c) return options.ContextOption(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
} }

829
redis.go
View File

@ -2,290 +2,121 @@ package redis
import ( import (
"context" "context"
"errors" "fmt"
"reflect" "reflect"
"strings" "strings"
"sync"
"sync/atomic"
"time" "time"
goredis "github.com/redis/go-redis/v9" "github.com/redis/go-redis/v9"
"go.unistack.org/micro/v3/semconv" "go.unistack.org/micro/v4/options"
"go.unistack.org/micro/v3/store" "go.unistack.org/micro/v4/store"
"go.unistack.org/micro/v3/util/id"
pool "go.unistack.org/micro/v3/util/xpool"
)
var (
_ store.Store = (*Store)(nil)
_ store.Event = (*event)(nil)
sendEventTime = 10 * time.Millisecond
DefaultUniversalOptions = &goredis.UniversalOptions{
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,
}
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: "",
Password: "", // no password set
DB: 0, // use default DB
MaxRetries: 2,
MaxRetryBackoff: 256 * time.Millisecond,
DialTimeout: 1 * time.Second,
ReadTimeout: 1 * time.Second,
WriteTimeout: 1 * time.Second,
PoolTimeout: 1 * time.Second,
MinIdleConns: 10,
}
) )
type Store struct { type Store struct {
cli goredis.UniversalClient
pool *pool.StringsPool
connected *atomic.Uint32
opts store.Options opts store.Options
watchers map[string]*watcher cli redis.UniversalClient
mu sync.RWMutex
}
func (r *Store) Live() bool {
return r.connected.Load() == 1
}
func (r *Store) Ready() bool {
return r.connected.Load() == 1
}
func (r *Store) Health() bool {
return r.connected.Load() == 1
} }
func (r *Store) Connect(ctx context.Context) error { func (r *Store) Connect(ctx context.Context) error {
if r.connected.Load() == 1 { return r.cli.Ping(ctx).Err()
return nil
}
if r.cli == nil {
return store.ErrNotConnected
}
if r.opts.LazyConnect {
return nil
}
if err := r.cli.Ping(ctx).Err(); err != nil {
setSpanError(ctx, err)
return err
}
r.connected.Store(1)
return nil
} }
func (r *Store) Init(opts ...store.Option) error { func (r *Store) Init(opts ...options.Option) error {
err := r.configure(opts...) return r.configure(opts...)
if err != nil {
return err
}
return nil
} }
func (r *Store) Client() *goredis.Client { func (r *Store) Redis() redis.UniversalClient {
if c, ok := r.cli.(*goredis.Client); ok {
return c
}
return nil
}
func (r *Store) UniversalClient() goredis.UniversalClient {
return r.cli return r.cli
} }
func (r *Store) ClusterClient() *goredis.ClusterClient {
if c, ok := r.cli.(*goredis.ClusterClient); ok {
return c
}
return nil
}
func (r *Store) Disconnect(ctx context.Context) error { func (r *Store) Disconnect(ctx context.Context) error {
if r.connected.Load() == 0 { return r.cli.Close()
return nil
}
if r.cli != nil {
if err := r.cli.Close(); err != nil {
return err
}
}
r.connected.Store(1)
return nil
} }
func (r *Store) Exists(ctx context.Context, key string, opts ...store.ExistsOption) error { func (r *Store) Exists(ctx context.Context, key string, opts ...options.Option) error {
b := r.pool.Get() if r.opts.Timeout > 0 {
defer r.pool.Put(b) var cancel context.CancelFunc
ctx, cancel = context.WithTimeout(ctx, r.opts.Timeout)
defer cancel()
}
options := store.NewExistsOptions(opts...) options := store.NewExistsOptions(opts...)
labels := make([]string, 0, 6) if len(options.Namespace) == 0 {
labels = append(labels, "name", options.Name, "statement", "exists") options.Namespace = r.opts.Namespace
timeout := r.opts.Timeout
if options.Timeout > 0 {
timeout = options.Timeout
} }
if options.Namespace != "" {
if timeout > 0 { key = fmt.Sprintf("%s%s", r.opts.Namespace, key)
var cancel context.CancelFunc
ctx, cancel = context.WithTimeout(ctx, timeout)
defer cancel()
} }
val, err := r.cli.Exists(ctx, key).Result()
rkey := r.getKey(b, r.opts.Namespace, options.Namespace, key) if err != nil {
r.opts.Meter.Counter(semconv.StoreRequestInflight, labels...).Inc()
ts := time.Now()
val, err := r.cli.Exists(ctx, rkey).Result()
setSpanError(ctx, err)
te := time.Since(ts)
r.opts.Meter.Counter(semconv.StoreRequestInflight, labels...).Dec()
r.opts.Meter.Summary(semconv.StoreRequestLatencyMicroseconds, labels...).Update(te.Seconds())
r.opts.Meter.Histogram(semconv.StoreRequestDurationSeconds, labels...).Update(te.Seconds())
if errors.Is(err, goredis.Nil) || (err == nil && val == 0) {
r.opts.Meter.Counter(semconv.StoreRequestTotal, append(labels, "status", "miss")...).Inc()
return store.ErrNotFound
} else if err == nil {
r.opts.Meter.Counter(semconv.StoreRequestTotal, append(labels, "status", "hit")...).Inc()
} else {
r.opts.Meter.Counter(semconv.StoreRequestTotal, append(labels, "status", "failure")...).Inc()
return err return err
} }
if val == 0 {
return store.ErrNotFound
}
return nil return nil
} }
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 ...options.Option) error {
b := r.pool.Get() if r.opts.Timeout > 0 {
defer r.pool.Put(b)
options := store.NewReadOptions(opts...)
labels := make([]string, 0, 6)
labels = append(labels, "name", options.Name, "statement", "read")
timeout := r.opts.Timeout
if options.Timeout > 0 {
timeout = options.Timeout
}
if timeout > 0 {
var cancel context.CancelFunc var cancel context.CancelFunc
ctx, cancel = context.WithTimeout(ctx, timeout) ctx, cancel = context.WithTimeout(ctx, r.opts.Timeout)
defer cancel() defer cancel()
} }
options := store.NewReadOptions(opts...)
if len(options.Namespace) == 0 {
options.Namespace = r.opts.Namespace
}
if options.Namespace != "" {
key = fmt.Sprintf("%s%s", options.Namespace, key)
}
rkey := r.getKey(b, r.opts.Namespace, options.Namespace, key) buf, err := r.cli.Get(ctx, key).Bytes()
if err != nil && err == redis.Nil {
r.opts.Meter.Counter(semconv.StoreRequestInflight, labels...).Inc()
ts := time.Now()
buf, err := r.cli.Get(ctx, rkey).Bytes()
setSpanError(ctx, err)
te := time.Since(ts)
r.opts.Meter.Counter(semconv.StoreRequestInflight, labels...).Dec()
r.opts.Meter.Summary(semconv.StoreRequestLatencyMicroseconds, labels...).Update(te.Seconds())
r.opts.Meter.Histogram(semconv.StoreRequestDurationSeconds, labels...).Update(te.Seconds())
if errors.Is(err, goredis.Nil) || (err == nil && buf == nil) {
r.opts.Meter.Counter(semconv.StoreRequestTotal, append(labels, "status", "miss")...).Inc()
return store.ErrNotFound return store.ErrNotFound
} else if err == nil {
r.opts.Meter.Counter(semconv.StoreRequestTotal, append(labels, "status", "hit")...).Inc()
} else if err != nil { } else if err != nil {
r.opts.Meter.Counter(semconv.StoreRequestTotal, append(labels, "status", "failure")...).Inc()
return err return err
} }
if buf == nil {
switch b := val.(type) { return store.ErrNotFound
case *[]byte:
*b = buf
case *string:
*b = string(buf)
default:
if err = r.opts.Codec.Unmarshal(buf, val); err != nil {
setSpanError(ctx, err)
} }
} return r.opts.Codec.Unmarshal(buf, val)
return err
} }
func (r *Store) MRead(ctx context.Context, keys []string, vals interface{}, opts ...store.ReadOption) error { func (r *Store) MRead(ctx context.Context, keys []string, vals interface{}, opts ...options.Option) error {
options := store.NewReadOptions(opts...) if len(keys) == 1 {
vt := reflect.ValueOf(vals)
timeout := r.opts.Timeout if vt.Kind() == reflect.Ptr {
if options.Timeout > 0 { vt = reflect.Indirect(vt)
timeout = options.Timeout return r.Read(ctx, keys[0], vt.Index(0).Interface(), opts...)
} }
}
if timeout > 0 { if r.opts.Timeout > 0 {
var cancel context.CancelFunc var cancel context.CancelFunc
ctx, cancel = context.WithTimeout(ctx, timeout) ctx, cancel = context.WithTimeout(ctx, r.opts.Timeout)
defer cancel() defer cancel()
} }
options := store.NewReadOptions(opts...)
var rkeys []string rkeys := make([]string, 0, len(keys))
var pools []*strings.Builder if len(options.Namespace) == 0 {
if r.opts.Namespace != "" || options.Namespace != "" { options.Namespace = r.opts.Namespace
rkeys = make([]string, len(keys))
pools = make([]*strings.Builder, len(keys))
for idx, key := range keys {
b := r.pool.Get()
pools[idx] = b
rkeys[idx] = r.getKey(b, r.opts.Namespace, options.Namespace, key)
}
}
r.opts.Meter.Counter(semconv.StoreRequestInflight, "name", options.Name).Inc()
ts := time.Now()
var rvals []interface{}
var err error
if r.opts.Namespace != "" || options.Namespace != "" {
rvals, err = r.cli.MGet(ctx, rkeys...).Result()
for idx := range pools {
r.pool.Put(pools[idx])
} }
for _, key := range keys {
if options.Namespace != "" {
rkeys = append(rkeys, fmt.Sprintf("%s%s", options.Namespace, key))
} else { } else {
rvals, err = r.cli.MGet(ctx, keys...).Result() rkeys = append(rkeys, key)
} }
setSpanError(ctx, err) }
te := time.Since(ts)
r.opts.Meter.Counter(semconv.StoreRequestInflight, "name", options.Name).Dec() rvals, err := r.cli.MGet(ctx, rkeys...).Result()
r.opts.Meter.Summary(semconv.StoreRequestLatencyMicroseconds, "name", options.Name).Update(te.Seconds()) if err != nil && err == redis.Nil {
r.opts.Meter.Histogram(semconv.StoreRequestDurationSeconds, "name", options.Name).Update(te.Seconds())
if err == goredis.Nil || (len(rvals) == 0) {
r.opts.Meter.Counter(semconv.StoreRequestTotal, "name", options.Name, "status", "miss").Inc()
return store.ErrNotFound return store.ErrNotFound
} else if err == nil {
r.opts.Meter.Counter(semconv.StoreRequestTotal, "name", options.Name, "status", "hit").Inc()
} else if err != nil { } else if err != nil {
r.opts.Meter.Counter(semconv.StoreRequestTotal, "name", options.Name, "status", "failure").Inc()
return err return err
} }
if len(rvals) == 0 {
return store.ErrNotFound
}
vv := reflect.ValueOf(vals) vv := reflect.ValueOf(vals)
vt := reflect.TypeOf(vals) vt := reflect.TypeOf(vals)
@ -315,144 +146,77 @@ func (r *Store) MRead(ctx context.Context, keys []string, vals interface{}, opts
// special case for raw data // special case for raw data
if vt.Kind() == reflect.Slice && vt.Elem().Kind() == reflect.Uint8 { if vt.Kind() == reflect.Slice && vt.Elem().Kind() == reflect.Uint8 {
itm.Set(reflect.MakeSlice(itm.Type(), len(buf), len(buf))) itm.Set(reflect.MakeSlice(itm.Type(), len(buf), len(buf)))
itm.SetBytes(buf) } else {
continue
} else if vt.Kind() == reflect.String {
itm.SetString(string(buf))
continue
}
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 {
setSpanError(ctx, err)
return err return err
} }
} }
vv.Set(nvv) vv.Set(nvv)
return nil return nil
} }
func (r *Store) MDelete(ctx context.Context, keys []string, opts ...store.DeleteOption) error { func (r *Store) MDelete(ctx context.Context, keys []string, opts ...options.Option) error {
options := store.NewDeleteOptions(opts...) if len(keys) == 1 {
labels := make([]string, 0, 6) return r.Delete(ctx, keys[0], opts...)
labels = append(labels, "name", options.Name, "statement", "delete")
timeout := r.opts.Timeout
if options.Timeout > 0 {
timeout = options.Timeout
} }
if r.opts.Timeout > 0 {
if timeout > 0 {
var cancel context.CancelFunc var cancel context.CancelFunc
ctx, cancel = context.WithTimeout(ctx, timeout) ctx, cancel = context.WithTimeout(ctx, r.opts.Timeout)
defer cancel() defer cancel()
} }
options := store.NewDeleteOptions(opts...)
var rkeys []string if len(options.Namespace) == 0 {
var pools []*strings.Builder options.Namespace = r.opts.Namespace
if r.opts.Namespace != "" || options.Namespace != "" {
rkeys = make([]string, len(keys))
pools = make([]*strings.Builder, len(keys))
for idx, key := range keys {
b := r.pool.Get()
pools[idx] = b
rkeys[idx] = r.getKey(b, r.opts.Namespace, options.Namespace, key)
} }
if options.Namespace == "" {
return r.cli.Del(ctx, keys...).Err()
} }
for idx := range keys {
r.opts.Meter.Counter(semconv.StoreRequestInflight, labels...).Inc() keys[idx] = options.Namespace + keys[idx]
ts := time.Now()
var err error
if r.opts.Namespace != "" || options.Namespace != "" {
err = r.cli.Del(ctx, rkeys...).Err()
for idx := range pools {
r.pool.Put(pools[idx])
} }
} else { return r.cli.Del(ctx, keys...).Err()
err = r.cli.Del(ctx, keys...).Err()
}
setSpanError(ctx, err)
te := time.Since(ts)
r.opts.Meter.Counter(semconv.StoreRequestInflight, labels...).Dec()
r.opts.Meter.Summary(semconv.StoreRequestLatencyMicroseconds, labels...).Update(te.Seconds())
r.opts.Meter.Histogram(semconv.StoreRequestDurationSeconds, labels...).Update(te.Seconds())
if err == goredis.Nil {
r.opts.Meter.Counter(semconv.StoreRequestTotal, append(labels, "status", "miss")...).Inc()
return store.ErrNotFound
} else if err == nil {
r.opts.Meter.Counter(semconv.StoreRequestTotal, append(labels, "status", "hit")...).Inc()
} else if err != nil {
r.opts.Meter.Counter(semconv.StoreRequestTotal, append(labels, "status", "failure")...).Inc()
return err
}
return nil
} }
func (r *Store) Delete(ctx context.Context, key string, opts ...store.DeleteOption) error { func (r *Store) Delete(ctx context.Context, key string, opts ...options.Option) error {
b := r.pool.Get() if r.opts.Timeout > 0 {
defer r.pool.Put(b)
options := store.NewDeleteOptions(opts...)
labels := make([]string, 0, 6)
labels = append(labels, "name", options.Name, "statement", "delete")
timeout := r.opts.Timeout
if options.Timeout > 0 {
timeout = options.Timeout
}
if timeout > 0 {
var cancel context.CancelFunc var cancel context.CancelFunc
ctx, cancel = context.WithTimeout(ctx, timeout) ctx, cancel = context.WithTimeout(ctx, r.opts.Timeout)
defer cancel() defer cancel()
} }
options := store.NewDeleteOptions(opts...)
r.opts.Meter.Counter(semconv.StoreRequestInflight, labels...).Inc() if len(options.Namespace) == 0 {
ts := time.Now() options.Namespace = r.opts.Namespace
err := r.cli.Del(ctx, r.getKey(b, r.opts.Namespace, options.Namespace, key)).Err()
te := time.Since(ts)
setSpanError(ctx, err)
r.opts.Meter.Counter(semconv.StoreRequestInflight, labels...).Dec()
r.opts.Meter.Summary(semconv.StoreRequestLatencyMicroseconds, labels...).Update(te.Seconds())
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
} else if err == nil {
r.opts.Meter.Counter(semconv.StoreRequestTotal, append(labels, "status", "hit")...).Inc()
} else if err != nil {
r.opts.Meter.Counter(semconv.StoreRequestTotal, append(labels, "status", "failure")...).Inc()
return err
} }
if options.Namespace == "" {
return nil return r.cli.Del(ctx, key).Err()
}
return r.cli.Del(ctx, fmt.Sprintf("%s%s", options.Namespace, key)).Err()
} }
func (r *Store) MWrite(ctx context.Context, keys []string, vals []interface{}, opts ...store.WriteOption) error { func (r *Store) MWrite(ctx context.Context, keys []string, vals []interface{}, opts ...options.Option) error {
if len(keys) == 1 {
return r.Write(ctx, keys[0], vals[0], opts...)
}
if r.opts.Timeout > 0 {
var cancel context.CancelFunc
ctx, cancel = context.WithTimeout(ctx, r.opts.Timeout)
defer cancel()
}
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
if options.Timeout > 0 {
timeout = options.Timeout
}
if timeout > 0 {
var cancel context.CancelFunc
ctx, cancel = context.WithTimeout(ctx, timeout)
defer cancel()
}
kvs := make([]string, 0, len(keys)*2) kvs := make([]string, 0, len(keys)*2)
pools := make([]*strings.Builder, len(keys))
if len(options.Namespace) == 0 {
options.Namespace = r.opts.Namespace
}
for idx, key := range keys { for idx, key := range keys {
b := r.pool.Get() if options.Namespace != "" {
pools[idx] = b kvs = append(kvs, fmt.Sprintf("%s%s", options.Namespace, key))
kvs = append(kvs, r.getKey(b, r.opts.Namespace, options.Namespace, key)) } else {
kvs = append(kvs, key)
}
switch vt := vals[idx].(type) { switch vt := vals[idx].(type) {
case string: case string:
@ -468,47 +232,21 @@ func (r *Store) MWrite(ctx context.Context, keys []string, vals []interface{}, o
} }
} }
r.opts.Meter.Counter(semconv.StoreRequestInflight, labels...).Inc() cmds, err := r.cli.Pipelined(ctx, func(pipe redis.Pipeliner) error {
var err 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
} })
if err != nil {
ts := time.Now()
cmds, err := r.cli.Pipelined(ctx, pipeliner)
for idx := range pools {
r.pool.Put(pools[idx])
}
te := time.Since(ts)
setSpanError(ctx, err)
r.opts.Meter.Counter(semconv.StoreRequestInflight, labels...).Dec()
r.opts.Meter.Summary(semconv.StoreRequestLatencyMicroseconds, labels...).Update(te.Seconds())
r.opts.Meter.Histogram(semconv.StoreRequestDurationSeconds, labels...).Update(te.Seconds())
if err == goredis.Nil {
r.opts.Meter.Counter(semconv.StoreRequestTotal, append(labels, "status", "miss")...).Inc()
return store.ErrNotFound
} else if err == nil {
r.opts.Meter.Counter(semconv.StoreRequestTotal, append(labels, "status", "hit")...).Inc()
} else if err != nil {
r.opts.Meter.Counter(semconv.StoreRequestTotal, append(labels, "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 == goredis.Nil {
r.opts.Meter.Counter(semconv.StoreRequestTotal, append(labels, "status", "miss")...).Inc()
return store.ErrNotFound
}
setSpanError(ctx, err)
r.opts.Meter.Counter(semconv.StoreRequestTotal, append(labels, "status", "failure")...).Inc()
return err return err
} }
} }
@ -516,26 +254,17 @@ func (r *Store) MWrite(ctx context.Context, keys []string, vals []interface{}, o
return nil return nil
} }
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 ...options.Option) error {
b := r.pool.Get() if r.opts.Timeout > 0 {
defer r.pool.Put(b)
options := store.NewWriteOptions(opts...)
labels := make([]string, 0, 6)
labels = append(labels, "name", options.Name, "statement", "write")
timeout := r.opts.Timeout
if options.Timeout > 0 {
timeout = options.Timeout
}
if timeout > 0 {
var cancel context.CancelFunc var cancel context.CancelFunc
ctx, cancel = context.WithTimeout(ctx, timeout) ctx, cancel = context.WithTimeout(ctx, r.opts.Timeout)
defer cancel() defer cancel()
} }
rkey := r.getKey(b, r.opts.Namespace, options.Namespace, key) options := store.NewWriteOptions(opts...)
if len(options.Namespace) == 0 {
options.Namespace = r.opts.Namespace
}
var buf []byte var buf []byte
switch vt := val.(type) { switch vt := val.(type) {
@ -551,103 +280,42 @@ func (r *Store) Write(ctx context.Context, key string, val interface{}, opts ...
} }
} }
r.opts.Meter.Counter(semconv.StoreRequestInflight, labels...).Inc() if options.Namespace != "" {
ts := time.Now() key = fmt.Sprintf("%s%s", options.Namespace, key)
err := r.cli.Set(ctx, rkey, buf, options.TTL).Err()
te := time.Since(ts)
setSpanError(ctx, err)
r.opts.Meter.Counter(semconv.StoreRequestInflight, labels...).Dec()
r.opts.Meter.Summary(semconv.StoreRequestLatencyMicroseconds, labels...).Update(te.Seconds())
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
} else if err == nil {
r.opts.Meter.Counter(semconv.StoreRequestTotal, append(labels, "status", "hit")...).Inc()
} else {
r.opts.Meter.Counter(semconv.StoreRequestTotal, append(labels, "status", "failure")...).Inc()
return err
} }
return err return r.cli.Set(ctx, key, buf, options.TTL).Err()
} }
func (r *Store) List(ctx context.Context, opts ...store.ListOption) ([]string, error) { func (r *Store) List(ctx context.Context, opts ...options.Option) ([]string, error) {
b := r.pool.Get()
defer r.pool.Put(b)
options := store.NewListOptions(opts...) options := store.NewListOptions(opts...)
labels := make([]string, 0, 6)
labels = append(labels, "name", options.Name, "statement", "list")
if len(options.Namespace) == 0 { if len(options.Namespace) == 0 {
options.Namespace = r.opts.Namespace options.Namespace = r.opts.Namespace
} }
rkey := r.getKey(b, options.Namespace, "", options.Prefix+"*") rkey := fmt.Sprintf("%s%s*", options.Namespace, options.Prefix)
if options.Suffix != "" { if options.Suffix != "" {
rkey += options.Suffix rkey += options.Suffix
} }
if r.opts.Timeout > 0 {
timeout := r.opts.Timeout
if options.Timeout > 0 {
timeout = options.Timeout
}
if timeout > 0 {
var cancel context.CancelFunc var cancel context.CancelFunc
ctx, cancel = context.WithTimeout(ctx, timeout) ctx, cancel = context.WithTimeout(ctx, r.opts.Timeout)
defer cancel() defer cancel()
} }
// TODO: add support for prefix/suffix/limit // TODO: add support for prefix/suffix/limit
r.opts.Meter.Counter(semconv.StoreRequestInflight, labels...).Inc() keys, err := r.cli.Keys(ctx, rkey).Result()
ts := time.Now() if err != nil {
var keys []string
var err error
if c, ok := r.cli.(*goredis.ClusterClient); ok {
err = c.ForEachMaster(ctx, func(nctx context.Context, cli *goredis.Client) error {
nkeys, nerr := cli.Keys(nctx, rkey).Result()
if nerr != nil {
return nerr
}
keys = append(keys, nkeys...)
return nil
})
} else {
keys, err = r.cli.Keys(ctx, rkey).Result()
}
te := time.Since(ts)
setSpanError(ctx, err)
r.opts.Meter.Counter(semconv.StoreRequestInflight, labels...).Dec()
r.opts.Meter.Summary(semconv.StoreRequestLatencyMicroseconds, labels...).Update(te.Seconds())
r.opts.Meter.Histogram(semconv.StoreRequestDurationSeconds, labels...).Update(te.Seconds())
if err == goredis.Nil {
r.opts.Meter.Counter(semconv.StoreRequestTotal, append(labels, "status", "miss")...).Inc()
return nil, store.ErrNotFound
} else if err == nil {
r.opts.Meter.Counter(semconv.StoreRequestTotal, append(labels, "status", "git")...).Inc()
} else if err != nil {
r.opts.Meter.Counter(semconv.StoreRequestTotal, append(labels, "status", "failure")...).Inc()
return nil, err return nil, err
} }
if options.Namespace == "" {
prefix := r.opts.Namespace
if options.Namespace != "" {
prefix = options.Namespace
}
if prefix == "" {
return keys, nil return keys, nil
} }
for idx, key := range keys { nkeys := make([]string, 0, len(keys))
keys[idx] = strings.TrimPrefix(key, prefix) for _, key := range keys {
nkeys = append(nkeys, strings.TrimPrefix(key, options.Namespace))
} }
return nkeys, nil
return keys, nil
} }
func (r *Store) Options() store.Options { func (r *Store) Options() store.Options {
@ -662,215 +330,60 @@ func (r *Store) String() string {
return "redis" return "redis"
} }
func NewStore(opts ...store.Option) *Store { func NewStore(opts ...options.Option) *Store {
b := atomic.Uint32{} return &Store{opts: store.NewOptions(opts...)}
return &Store{
opts: store.NewOptions(opts...),
connected: &b,
watchers: make(map[string]*watcher),
}
} }
func (r *Store) configure(opts ...store.Option) error { func (r *Store) configure(opts ...options.Option) error {
if r.cli != nil && len(opts) == 0 { if r.cli != nil && len(opts) == 0 {
return nil return nil
} }
for _, o := range opts { var redisUniversalOptions *redis.UniversalOptions
o(&r.opts) var err error
}
universalOptions := DefaultUniversalOptions for _, o := range opts {
if err = o(r.opts); err != nil {
return err
}
}
if r.opts.Context != nil { if r.opts.Context != nil {
if o, ok := r.opts.Context.Value(configKey{}).(*goredis.Options); ok { if c, ok := r.opts.Context.Value(universalConfigKey{}).(*redis.UniversalOptions); ok {
universalOptions.Addrs = []string{o.Addr} redisUniversalOptions = c
universalOptions.Dialer = o.Dialer if r.opts.TLSConfig != nil {
universalOptions.OnConnect = o.OnConnect redisUniversalOptions.TLSConfig = r.opts.TLSConfig
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 o.TLSConfig != nil {
universalOptions.TLSConfig = o.TLSConfig
}
}
if o, ok := r.opts.Context.Value(clusterConfigKey{}).(*goredis.ClusterOptions); ok {
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 o.TLSConfig != nil {
universalOptions.TLSConfig = o.TLSConfig
}
}
if o, ok := r.opts.Context.Value(universalConfigKey{}).(*goredis.UniversalOptions); ok {
universalOptions = o
if o.TLSConfig != nil {
universalOptions.TLSConfig = o.TLSConfig
} }
} }
} }
if len(r.opts.Addrs) > 0 { if redisUniversalOptions == nil && r.cli != nil {
universalOptions.Addrs = r.opts.Addrs return nil
} else {
universalOptions.Addrs = []string{"127.0.0.1:6379"}
} }
r.cli = goredis.NewUniversalClient(universalOptions) if redisUniversalOptions == nil {
setTracing(r.cli, r.opts.Tracer) redisUniversalOptions = &redis.UniversalOptions{
r.cli.AddHook(newEventHook(r)) Username: "",
Password: "", // no password set
DB: 0, // use default DB
MaxRetries: 2,
MaxRetryBackoff: 256 * time.Millisecond,
DialTimeout: 1 * time.Second,
ReadTimeout: 1 * time.Second,
WriteTimeout: 1 * time.Second,
PoolTimeout: 1 * time.Second,
MinIdleConns: 10,
TLSConfig: r.opts.TLSConfig,
}
}
r.pool = pool.NewStringsPool(50) if len(r.opts.Address) > 0 {
redisUniversalOptions.Addrs = r.opts.Address
} else if len(redisUniversalOptions.Addrs) == 0 {
redisUniversalOptions.Addrs = []string{"redis://127.0.0.1:6379"}
}
r.statsMeter() r.cli = redis.NewUniversalClient(redisUniversalOptions)
return nil return nil
} }
func (r *Store) getKey(b *strings.Builder, mainNamespace string, opNamespace string, key string) string {
if opNamespace == "" {
opNamespace = mainNamespace
}
if opNamespace != "" {
b.WriteString(opNamespace)
b.WriteString(r.opts.Separator)
}
b.WriteString(key)
return b.String()
}
func (r *Store) Watch(ctx context.Context, opts ...store.WatchOption) (store.Watcher, error) {
id, err := id.New()
if err != nil {
return nil, err
}
wo, err := store.NewWatchOptions(opts...)
if err != nil {
return nil, err
}
// construct the watcher
w := &watcher{
exit: make(chan bool),
ch: make(chan store.Event),
id: id,
opts: wo,
}
r.mu.Lock()
r.watchers[w.id] = w
r.mu.Unlock()
return w, nil
}
func (r *Store) sendEvent(e store.Event) {
r.mu.RLock()
watchers := make([]*watcher, 0, len(r.watchers))
for _, w := range r.watchers {
watchers = append(watchers, w)
}
r.mu.RUnlock()
for _, w := range watchers {
select {
case <-w.exit:
r.mu.Lock()
delete(r.watchers, w.id)
r.mu.Unlock()
default:
select {
case w.ch <- e:
case <-time.After(sendEventTime):
}
}
}
}
type watcher struct {
ch chan store.Event
exit chan bool
opts store.WatchOptions
id string
}
func (w *watcher) Next() (store.Event, error) {
for {
select {
case e := <-w.ch:
return e, nil
case <-w.exit:
return nil, store.ErrWatcherStopped
}
}
}
func (w *watcher) Stop() {
select {
case <-w.exit:
return
default:
close(w.exit)
}
}
type event struct {
ts time.Time
t store.EventType
err error
}
func (e *event) Error() error {
return e.err
}
func (e *event) Timestamp() time.Time {
return e.ts
}
func (e *event) Type() store.EventType {
return e.t
}

View File

@ -4,67 +4,18 @@ import (
"bytes" "bytes"
"context" "context"
"os" "os"
"sync/atomic"
"testing" "testing"
"time" "time"
goredis "github.com/redis/go-redis/v9" "github.com/redis/go-redis/v9"
"go.unistack.org/micro/v3/store" "go.unistack.org/micro/v4/options"
"go.unistack.org/micro/v3/tracer" "go.unistack.org/micro/v4/store"
) )
func TestLazyConnect(t *testing.T) {
t.Skip("skipping test for manual check")
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(store.LazyConnect(true)); 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 goredis.UniversalClient Client *redis.Client
} }
type wantValues struct { type wantValues struct {
username string username string
@ -87,7 +38,7 @@ func Test_rkv_configure(t *testing.T) {
}, },
}, },
{ {
name: "legacy Url", fields: fields{options: store.Options{Tracer: tracer.DefaultTracer, Addrs: []string{"127.0.0.1:6379"}}, Client: nil}, name: "legacy Url", fields: fields{options: store.Options{Address: []string{"127.0.0.1:6379"}}, Client: nil},
wantErr: false, want: wantValues{ wantErr: false, want: wantValues{
username: "", username: "",
password: "", password: "",
@ -95,7 +46,7 @@ func Test_rkv_configure(t *testing.T) {
}, },
}, },
{ {
name: "New Url", fields: fields{options: store.Options{Tracer: tracer.DefaultTracer, Addrs: []string{"redis://127.0.0.1:6379"}}, Client: nil}, name: "New Url", fields: fields{options: store.Options{Address: []string{"redis://127.0.0.1:6379"}}, Client: nil},
wantErr: false, want: wantValues{ wantErr: false, want: wantValues{
username: "", username: "",
password: "", password: "",
@ -103,7 +54,7 @@ func Test_rkv_configure(t *testing.T) {
}, },
}, },
{ {
name: "Url with Pwd", fields: fields{options: store.Options{Tracer: tracer.DefaultTracer, Addrs: []string{"redis://:password@redis:6379"}}, Client: nil}, name: "Url with Pwd", fields: fields{options: store.Options{Address: []string{"redis://:password@redis:6379"}}, Client: nil},
wantErr: false, want: wantValues{ wantErr: false, want: wantValues{
username: "", username: "",
password: "password", password: "password",
@ -111,7 +62,7 @@ func Test_rkv_configure(t *testing.T) {
}, },
}, },
{ {
name: "Url with username and Pwd", fields: fields{options: store.Options{Tracer: tracer.DefaultTracer, Addrs: []string{"redis://username:password@redis:6379"}}, Client: nil}, name: "Url with username and Pwd", fields: fields{options: store.Options{Address: []string{"redis://username:password@redis:6379"}}, Client: nil},
wantErr: false, want: wantValues{ wantErr: false, want: wantValues{
username: "username", username: "username",
password: "password", password: "password",
@ -121,11 +72,9 @@ func Test_rkv_configure(t *testing.T) {
} }
for _, tt := range tests { for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) { t.Run(tt.name, func(t *testing.T) {
b := atomic.Uint32{}
rc := &Store{ rc := &Store{
opts: tt.fields.options, opts: tt.fields.options,
cli: tt.fields.Client, cli: tt.fields.Client,
connected: &b,
} }
err := rc.configure() err := rc.configure()
if (err != nil) != tt.wantErr { if (err != nil) != tt.wantErr {
@ -142,7 +91,7 @@ func Test_Store(t *testing.T) {
if tr := os.Getenv("INTEGRATION_TESTS"); len(tr) > 0 { if tr := os.Getenv("INTEGRATION_TESTS"); len(tr) > 0 {
t.Skip() t.Skip()
} }
r := NewStore(store.Addrs(os.Getenv("STORE_NODES"))) r := NewStore(options.Address(os.Getenv("STORE_NODES")))
if err := r.Init(); err != nil { if err := r.Init(); err != nil {
t.Fatal(err) t.Fatal(err)
@ -182,7 +131,7 @@ func Test_MRead(t *testing.T) {
if tr := os.Getenv("INTEGRATION_TESTS"); len(tr) > 0 { if tr := os.Getenv("INTEGRATION_TESTS"); len(tr) > 0 {
t.Skip() t.Skip()
} }
r := NewStore(store.Addrs(os.Getenv("STORE_NODES"))) r := NewStore(options.Address(os.Getenv("STORE_NODES")))
if err = r.Init(); err != nil { if err = r.Init(); err != nil {
t.Fatal(err) t.Fatal(err)

View File

@ -1,49 +0,0 @@
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
View File

@ -1,128 +0,0 @@
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)
}