micro-store-redis/event.go
Evstigneev Denis 24f9f41de4
Some checks failed
codeql / analyze (go) (push) Failing after 1m2s
build / test (push) Failing after 5m0s
build / lint (push) Successful in 9m35s
add using lazy connect (#122)
Co-authored-by: Vasiliy Tolstov <v.tolstov@unistack.org>
Reviewed-on: #122
Co-authored-by: Evstigneev Denis <danteevstigneev@yandex.ru>
Co-committed-by: Evstigneev Denis <danteevstigneev@yandex.ru>
2024-11-27 01:57:39 +03:00

56 lines
1.2 KiB
Go

package redis
import (
"context"
"errors"
"net"
"sync/atomic"
goredis "github.com/redis/go-redis/v9"
)
type eventHook struct {
connected *atomic.Bool
}
var _ goredis.Hook = (*eventHook)(nil)
func newEventHook(connected *atomic.Bool) *eventHook {
return &eventHook{connected: connected}
}
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 && !isRedisError(err) {
h.connected.Store(false)
}
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 && !isRedisError(err) {
h.connected.Store(false)
}
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 && !isRedisError(err) {
h.connected.Store(false)
}
return err
}
}
func isRedisError(err error) bool {
var rerr goredis.Error
return errors.As(err, &rerr)
}