package redis
import (
"cmp"
"context"
"crypto/tls"
"errors"
"fmt"
"math"
"math/rand"
"net"
"net/url"
"runtime"
"slices"
"sort"
"strings"
"sync"
"sync/atomic"
"time"
"github.com/redis/go-redis/v9/auth"
"github.com/redis/go-redis/v9/internal"
"github.com/redis/go-redis/v9/internal/hashtag"
"github.com/redis/go-redis/v9/internal/otel"
"github.com/redis/go-redis/v9/internal/pool"
"github.com/redis/go-redis/v9/internal/proto"
"github.com/redis/go-redis/v9/internal/routing"
"github.com/redis/go-redis/v9/maintnotifications"
"github.com/redis/go-redis/v9/push"
)
const (
minLatencyMeasurementInterval = 10 * time .Second
)
var (
errClusterNoNodes = errors .New ("redis: cluster has no nodes" )
errNoWatchKeys = errors .New ("redis: Watch requires at least one key" )
errWatchCrosslot = errors .New ("redis: Watch requires all keys to be in the same slot" )
)
type ClusterOptions struct {
Addrs []string
ClientName string
NewClient func (opt *Options ) *Client
MaxRedirects int
ReadOnly bool
RouteByLatency bool
RouteByLatencyTolerance time .Duration
RouteRandomly bool
ClusterSlots func (context .Context ) ([]ClusterSlot , error )
Dialer func (ctx context .Context , network, addr string ) (net .Conn , error )
OnConnect func (ctx context .Context , cn *Conn ) error
Protocol int
Username string
Password string
CredentialsProvider func () (username string , password string )
CredentialsProviderContext func (ctx context .Context ) (username string , password string , err error )
StreamingCredentialsProvider auth .StreamingCredentialsProvider
MaxRetries int
MinRetryBackoff time .Duration
MaxRetryBackoff time .Duration
DialTimeout time .Duration
DialerRetries int
DialerRetryTimeout time .Duration
DialerRetryBackoff func (attempt int ) time .Duration
ReadTimeout time .Duration
WriteTimeout time .Duration
ContextTimeoutEnabled bool
MaxConcurrentDials int
PoolFIFO bool
PoolSize int
PoolTimeout time .Duration
MinIdleConns int
MaxIdleConns int
MaxActiveConns int
ConnMaxIdleTime time .Duration
ConnMaxLifetime time .Duration
ConnMaxLifetimeJitter time .Duration
ReadBufferSize int
WriteBufferSize int
PipelineReadBufferSize int
PipelineWriteBufferSize int
PipelinePoolSize int
AutoPipelineOptions *AutoPipelineOptions
TLSConfig *tls .Config
DisableRoutingPolicies bool
DisableIndentity bool
DisableIdentity bool
IdentitySuffix string
UnstableResp3 bool
PushNotificationProcessor push .NotificationProcessor
FailingTimeoutSeconds int
MaintNotificationsConfig *maintnotifications .Config
ShardPicker routing .ShardPicker
ClusterStateReloadInterval time .Duration
}
func (opt *ClusterOptions ) init () {
switch opt .MaxRedirects {
case -1 :
opt .MaxRedirects = 0
case 0 :
opt .MaxRedirects = 3
}
if opt .RouteByLatency || opt .RouteRandomly {
opt .ReadOnly = true
}
if opt .DialTimeout == 0 {
opt .DialTimeout = 5 * time .Second
}
if opt .DialerRetries == 0 {
opt .DialerRetries = 5
}
if opt .DialerRetryTimeout == 0 {
opt .DialerRetryTimeout = 100 * time .Millisecond
}
if opt .PoolSize == 0 {
opt .PoolSize = 5 * runtime .GOMAXPROCS (0 )
}
if opt .ReadBufferSize == 0 {
opt .ReadBufferSize = proto .DefaultBufferSize
}
if opt .WriteBufferSize == 0 {
opt .WriteBufferSize = proto .DefaultBufferSize
}
switch opt .ReadTimeout {
case -1 :
opt .ReadTimeout = 0
case 0 :
opt .ReadTimeout = 5 * time .Second
}
switch opt .WriteTimeout {
case -1 :
opt .WriteTimeout = 0
case 0 :
opt .WriteTimeout = opt .ReadTimeout
}
if opt .MaxRetries == 0 {
opt .MaxRetries = -1
}
switch opt .MinRetryBackoff {
case -1 :
opt .MinRetryBackoff = 0
case 0 :
opt .MinRetryBackoff = 10 * time .Millisecond
}
switch opt .MaxRetryBackoff {
case -1 :
opt .MaxRetryBackoff = 0
case 0 :
opt .MaxRetryBackoff = time .Second
}
if opt .NewClient == nil {
opt .NewClient = NewClient
}
if opt .FailingTimeoutSeconds == 0 {
opt .FailingTimeoutSeconds = 15
}
if opt .ShardPicker == nil {
opt .ShardPicker = &routing .RoundRobinPicker {}
}
if opt .ClusterStateReloadInterval == 0 {
opt .ClusterStateReloadInterval = 60 * time .Second
}
}
func ParseClusterURL (redisURL string ) (*ClusterOptions , error ) {
o := &ClusterOptions {}
u , err := url .Parse (redisURL )
if err != nil {
return nil , err
}
h , p := getHostPortWithDefaults (u )
o .Addrs = append (o .Addrs , net .JoinHostPort (h , p ))
o , err = setupClusterConn (u , h , o )
if err != nil {
return nil , err
}
return o , nil
}
func setupClusterConn(u *url .URL , host string , o *ClusterOptions ) (*ClusterOptions , error ) {
switch u .Scheme {
case "rediss" :
o .TLSConfig = &tls .Config {ServerName : host }
fallthrough
case "redis" :
o .Username , o .Password = getUserPassword (u )
default :
return nil , fmt .Errorf ("redis: invalid URL scheme: %s" , u .Scheme )
}
o , err := setupClusterQueryParams (u , o )
if err != nil {
return nil , err
}
return o , nil
}
func setupClusterQueryParams(u *url .URL , o *ClusterOptions ) (*ClusterOptions , error ) {
q := queryOptions {q : u .Query ()}
o .Protocol = q .int ("protocol" )
o .ClientName = q .string ("client_name" )
o .MaxRedirects = q .int ("max_redirects" )
o .ReadOnly = q .bool ("read_only" )
o .RouteByLatency = q .bool ("route_by_latency" )
o .RouteByLatencyTolerance = q .duration ("route_by_latency_tolerance" )
o .RouteRandomly = q .bool ("route_randomly" )
o .MaxRetries = q .int ("max_retries" )
o .MinRetryBackoff = q .duration ("min_retry_backoff" )
o .MaxRetryBackoff = q .duration ("max_retry_backoff" )
o .DialTimeout = q .duration ("dial_timeout" )
o .DialerRetries = q .int ("dialer_retries" )
o .DialerRetryTimeout = q .duration ("dialer_retry_timeout" )
o .ReadTimeout = q .duration ("read_timeout" )
o .WriteTimeout = q .duration ("write_timeout" )
o .PoolFIFO = q .bool ("pool_fifo" )
o .PoolSize = q .int ("pool_size" )
o .MaxConcurrentDials = q .int ("max_concurrent_dials" )
o .MinIdleConns = q .int ("min_idle_conns" )
o .MaxIdleConns = q .int ("max_idle_conns" )
o .MaxActiveConns = q .int ("max_active_conns" )
o .PipelinePoolSize = q .int ("pipeline_pool_size" )
o .PipelineReadBufferSize = q .int ("pipeline_read_buffer_size" )
o .PipelineWriteBufferSize = q .int ("pipeline_write_buffer_size" )
o .PoolTimeout = q .duration ("pool_timeout" )
o .ConnMaxLifetime = q .duration ("conn_max_lifetime" )
if q .has ("conn_max_lifetime_jitter" ) {
o .ConnMaxLifetimeJitter = min (q .duration ("conn_max_lifetime_jitter" ), o .ConnMaxLifetime )
}
o .ConnMaxIdleTime = q .duration ("conn_max_idle_time" )
o .FailingTimeoutSeconds = q .int ("failing_timeout_seconds" )
if q .err != nil {
return nil , q .err
}
addrs := q .strings ("addr" )
for _ , addr := range addrs {
h , p , err := net .SplitHostPort (addr )
if err != nil || h == "" || p == "" {
return nil , fmt .Errorf ("redis: unable to parse addr param: %s" , addr )
}
o .Addrs = append (o .Addrs , net .JoinHostPort (h , p ))
}
if r := q .remaining (); len (r ) > 0 {
return nil , fmt .Errorf ("redis: unexpected option: %s" , strings .Join (r , ", " ))
}
return o , nil
}
func (opt *ClusterOptions ) clientOptions () *Options {
var maintNotificationsConfig *maintnotifications .Config
if opt .MaintNotificationsConfig != nil {
configClone := *opt .MaintNotificationsConfig
maintNotificationsConfig = &configClone
}
return &Options {
ClientName : opt .ClientName ,
Dialer : opt .Dialer ,
OnConnect : opt .OnConnect ,
Protocol : opt .Protocol ,
Username : opt .Username ,
Password : opt .Password ,
CredentialsProvider : opt .CredentialsProvider ,
CredentialsProviderContext : opt .CredentialsProviderContext ,
StreamingCredentialsProvider : opt .StreamingCredentialsProvider ,
MaxRetries : opt .MaxRetries ,
MinRetryBackoff : opt .MinRetryBackoff ,
MaxRetryBackoff : opt .MaxRetryBackoff ,
DialTimeout : opt .DialTimeout ,
DialerRetries : opt .DialerRetries ,
DialerRetryTimeout : opt .DialerRetryTimeout ,
DialerRetryBackoff : opt .DialerRetryBackoff ,
ReadTimeout : opt .ReadTimeout ,
WriteTimeout : opt .WriteTimeout ,
ContextTimeoutEnabled : opt .ContextTimeoutEnabled ,
PoolFIFO : opt .PoolFIFO ,
PoolSize : opt .PoolSize ,
MaxConcurrentDials : opt .MaxConcurrentDials ,
PoolTimeout : opt .PoolTimeout ,
MinIdleConns : opt .MinIdleConns ,
MaxIdleConns : opt .MaxIdleConns ,
MaxActiveConns : opt .MaxActiveConns ,
ConnMaxIdleTime : opt .ConnMaxIdleTime ,
ConnMaxLifetime : opt .ConnMaxLifetime ,
ConnMaxLifetimeJitter : opt .ConnMaxLifetimeJitter ,
ReadBufferSize : opt .ReadBufferSize ,
WriteBufferSize : opt .WriteBufferSize ,
PipelineReadBufferSize : opt .PipelineReadBufferSize ,
PipelineWriteBufferSize : opt .PipelineWriteBufferSize ,
PipelinePoolSize : opt .PipelinePoolSize ,
DisableIdentity : opt .DisableIdentity ,
DisableIndentity : opt .DisableIndentity ,
IdentitySuffix : opt .IdentitySuffix ,
FailingTimeoutSeconds : opt .FailingTimeoutSeconds ,
TLSConfig : opt .TLSConfig ,
readOnly : opt .ReadOnly && opt .ClusterSlots == nil ,
UnstableResp3 : opt .UnstableResp3 ,
MaintNotificationsConfig : maintNotificationsConfig ,
PushNotificationProcessor : opt .PushNotificationProcessor ,
}
}
type clusterNode struct {
Client *Client
latency atomic .Uint32
generation atomic .Uint32
failing atomic .Uint32
loaded atomic .Uint32
lastLatencyMeasurement atomic .Int64
}
func newClusterNodeWithNodeAddress(clOpt *ClusterOptions , addr , nodeAddress string ) *clusterNode {
opt := clOpt .clientOptions ()
opt .Addr = addr
opt .NodeAddress = nodeAddress
if opt .ReadTimeout == 0 {
opt .ReadTimeout = -1
}
if opt .WriteTimeout == 0 {
opt .WriteTimeout = -1
}
node := clusterNode {
Client : clOpt .NewClient (opt ),
}
node .latency .Store (unmeasuredNodeLatencyMicros )
if clOpt .RouteByLatency {
go node .updateLatency ()
}
return &node
}
func (n *clusterNode ) String () string {
return n .Client .String ()
}
func (n *clusterNode ) Close () error {
return n .Client .Close ()
}
const maximumNodeLatency = 1 * time .Minute
const (
unmeasuredNodeLatencyMicros uint32 = math .MaxUint32
unmeasuredNodeLatency = time .Duration (unmeasuredNodeLatencyMicros ) * time .Microsecond
)
func (n *clusterNode ) updateLatency () {
const numProbe = 10
var dur uint64
successes := 0
for i := 0 ; i < numProbe ; i ++ {
time .Sleep (time .Duration (10 +rand .Intn (10 )) * time .Millisecond )
start := time .Now ()
err := n .Client .Ping (context .TODO ()).Err ()
if err == nil {
dur += uint64 (time .Since (start ) / time .Microsecond )
successes ++
}
}
var latency float64
if successes == 0 {
latency = float64 (maximumNodeLatency / time .Microsecond )
} else {
latency = float64 (dur ) / float64 (successes )
}
n .latency .Store (uint32 (latency + 0.5 ))
n .SetLastLatencyMeasurement (time .Now ())
}
func (n *clusterNode ) Latency () time .Duration {
latency := n .latency .Load ()
return time .Duration (latency ) * time .Microsecond
}
func (n *clusterNode ) MarkAsFailing () {
n .failing .Store (uint32 (time .Now ().Unix ()))
n .loaded .Store (0 )
}
func (n *clusterNode ) Failing () bool {
timeout := int64 (n .Client .opt .FailingTimeoutSeconds )
failing := n .failing .Load ()
if failing == 0 {
return false
}
if time .Now ().Unix ()-int64 (failing ) < timeout {
return true
}
n .failing .Store (0 )
return false
}
func (n *clusterNode ) Generation () uint32 {
return n .generation .Load ()
}
func (n *clusterNode ) LastLatencyMeasurement () int64 {
return n .lastLatencyMeasurement .Load ()
}
func (n *clusterNode ) SetGeneration (gen uint32 ) {
for {
v := n .generation .Load ()
if gen < v || n .generation .CompareAndSwap (v , gen ) {
break
}
}
}
func (n *clusterNode ) SetLastLatencyMeasurement (t time .Time ) {
for {
v := n .lastLatencyMeasurement .Load ()
if t .UnixNano () < v || n .lastLatencyMeasurement .CompareAndSwap (v , t .UnixNano ()) {
break
}
}
}
func (n *clusterNode ) Loading () bool {
loaded := n .loaded .Load ()
if loaded == 1 {
return false
}
ctx , cancel := context .WithTimeout (context .Background (), 100 *time .Millisecond )
defer cancel ()
err := n .Client .Ping (ctx ).Err ()
loading := err != nil && isLoadingError (err )
if !loading {
n .loaded .Store (1 )
}
return loading
}
type clusterNodes struct {
opt *ClusterOptions
mu sync .RWMutex
addrs []string
nodes map [string ]*clusterNode
activeAddrs []string
closed bool
onNewNode []func (rdb *Client )
generation atomic .Uint32
}
func newClusterNodes(opt *ClusterOptions ) *clusterNodes {
return &clusterNodes {
opt : opt ,
addrs : opt .Addrs ,
nodes : make (map [string ]*clusterNode ),
}
}
func (c *clusterNodes ) Close () error {
c .mu .Lock ()
defer c .mu .Unlock ()
if c .closed {
return nil
}
c .closed = true
var firstErr error
for _ , node := range c .nodes {
if err := node .Client .Close (); err != nil && firstErr == nil {
firstErr = err
}
}
c .nodes = nil
c .activeAddrs = nil
return firstErr
}
func (c *clusterNodes ) OnNewNode (fn func (rdb *Client )) {
c .mu .Lock ()
c .onNewNode = append (c .onNewNode , fn )
c .mu .Unlock ()
}
func (c *clusterNodes ) Addrs () ([]string , error ) {
var addrs []string
c .mu .RLock ()
closed := c .closed
if !closed {
if len (c .activeAddrs ) > 0 {
addrs = make ([]string , len (c .activeAddrs ))
copy (addrs , c .activeAddrs )
} else {
addrs = make ([]string , len (c .addrs ))
copy (addrs , c .addrs )
}
}
c .mu .RUnlock ()
if closed {
return nil , pool .ErrClosed
}
if len (addrs ) == 0 {
return nil , errClusterNoNodes
}
return addrs , nil
}
func (c *clusterNodes ) NextGeneration () uint32 {
return c .generation .Add (1 )
}
func (c *clusterNodes ) GC (generation uint32 ) {
var collected []*clusterNode
c .mu .Lock ()
c .activeAddrs = c .activeAddrs [:0 ]
now := time .Now ()
for addr , node := range c .nodes {
if node .Generation () >= generation {
c .activeAddrs = append (c .activeAddrs , addr )
if c .opt .RouteByLatency && node .LastLatencyMeasurement () < now .Add (-minLatencyMeasurementInterval ).UnixNano () {
go node .updateLatency ()
}
continue
}
delete (c .nodes , addr )
collected = append (collected , node )
}
c .mu .Unlock ()
for _ , node := range collected {
_ = node .Client .Close ()
}
}
func (c *clusterNodes ) GetOrCreate (addr string ) (*clusterNode , error ) {
return c .GetOrCreateWithNodeAddress (addr , "" )
}
func (c *clusterNodes ) GetOrCreateWithNodeAddress (addr , nodeAddress string ) (*clusterNode , error ) {
node , err := c .get (addr )
if err != nil {
return nil , err
}
if node != nil {
return node , nil
}
c .mu .Lock ()
defer c .mu .Unlock ()
if c .closed {
return nil , pool .ErrClosed
}
node , ok := c .nodes [addr ]
if ok {
return node , nil
}
node = newClusterNodeWithNodeAddress (c .opt , addr , nodeAddress )
for _ , fn := range c .onNewNode {
fn (node .Client )
}
c .addrs = appendIfNotExist (c .addrs , addr )
c .nodes [addr ] = node
return node , nil
}
func (c *clusterNodes ) get (addr string ) (*clusterNode , error ) {
c .mu .RLock ()
defer c .mu .RUnlock ()
if c .closed {
return nil , pool .ErrClosed
}
return c .nodes [addr ], nil
}
func (c *clusterNodes ) All () ([]*clusterNode , error ) {
c .mu .RLock ()
defer c .mu .RUnlock ()
if c .closed {
return nil , pool .ErrClosed
}
cp := make ([]*clusterNode , 0 , len (c .nodes ))
for _ , node := range c .nodes {
cp = append (cp , node )
}
return cp , nil
}
func (c *clusterNodes ) Random () (*clusterNode , error ) {
addrs , err := c .Addrs ()
if err != nil {
return nil , err
}
n := rand .Intn (len (addrs ))
return c .GetOrCreate (addrs [n ])
}
type clusterSlot struct {
start int
end int
nodes []*clusterNode
latencyBandNodeCursor atomic .Uint32
}
type clusterState struct {
nodes *clusterNodes
Masters []*clusterNode
Slaves []*clusterNode
slots []*clusterSlot
generation uint32
createdAt time .Time
}
func newClusterState(
nodes *clusterNodes , slots []ClusterSlot , origin string ,
) (*clusterState , error ) {
c := clusterState {
nodes : nodes ,
slots : make ([]*clusterSlot , 0 , len (slots )),
generation : nodes .NextGeneration (),
createdAt : time .Now (),
}
originHost , originPort , _ := net .SplitHostPort (origin )
isLoopbackOrigin := isLoopback (originHost )
for _ , slot := range slots {
var nodes []*clusterNode
for i , slotNode := range slot .Nodes {
nodeAddress := slotNode .Addr
addr := nodeAddress
if !isLoopbackOrigin {
addr = replaceLoopbackHost (addr , originHost )
}
addr = replaceZeroPort (addr , originPort )
node , err := c .nodes .GetOrCreateWithNodeAddress (addr , nodeAddress )
if err != nil {
return nil , err
}
node .SetGeneration (c .generation )
nodes = append (nodes , node )
if i == 0 {
c .Masters = appendIfNotExist (c .Masters , node )
} else {
c .Slaves = appendIfNotExist (c .Slaves , node )
}
}
c .slots = append (c .slots , &clusterSlot {
start : slot .Start ,
end : slot .End ,
nodes : nodes ,
})
}
slices .SortFunc (c .slots , func (a , b *clusterSlot ) int {
return cmp .Compare (a .start , b .start )
})
time .AfterFunc (time .Minute , func () {
nodes .GC (c .generation )
})
return &c , nil
}
func replaceLoopbackHost(nodeAddr , originHost string ) string {
nodeHost , nodePort , err := net .SplitHostPort (nodeAddr )
if err != nil {
return nodeAddr
}
nodeIP := net .ParseIP (nodeHost )
if nodeIP == nil {
return nodeAddr
}
if !nodeIP .IsLoopback () {
return nodeAddr
}
return net .JoinHostPort (originHost , nodePort )
}
func replaceZeroPort(nodeAddr , originPort string ) string {
if originPort == "" || originPort == "0" {
return nodeAddr
}
nodeHost , nodePort , err := net .SplitHostPort (nodeAddr )
if err != nil || nodePort != "0" {
return nodeAddr
}
return net .JoinHostPort (nodeHost , originPort )
}
func isLoopback(host string ) bool {
ip := net .ParseIP (host )
if ip != nil {
return ip .IsLoopback ()
}
if strings .ToLower (host ) == "localhost" {
return true
}
if strings .HasSuffix (strings .ToLower (host ), ".docker.internal" ) {
return true
}
return false
}
func (c *clusterState ) slotMasterNode (slot int ) (*clusterNode , error ) {
nodes := c .slotNodes (slot )
if len (nodes ) > 0 {
return nodes [0 ], nil
}
return c .nodes .Random ()
}
func (c *clusterState ) slotSlaveNode (slot int ) (*clusterNode , error ) {
nodes := c .slotNodes (slot )
switch len (nodes ) {
case 0 :
return c .nodes .Random ()
case 1 :
return nodes [0 ], nil
case 2 :
slave := nodes [1 ]
if !slave .Failing () && !slave .Loading () {
return slave , nil
}
return nodes [0 ], nil
default :
var slave *clusterNode
for i := 0 ; i < 10 ; i ++ {
n := rand .Intn (len (nodes )-1 ) + 1
slave = nodes [n ]
if !slave .Failing () && !slave .Loading () {
return slave , nil
}
}
return nodes [0 ], nil
}
}
func (c *clusterState ) slotClosestNode (slot int ) (*clusterNode , error ) {
nodes := c .slotNodes (slot )
if len (nodes ) == 0 {
return c .nodes .Random ()
}
allNodesFailing := true
var (
closestNonFailingNode *clusterNode
closestNode *clusterNode
minLatency time .Duration
)
minLatency = time .Duration (math .MaxInt64 )
minNonFailingLatency := time .Duration (math .MaxInt64 )
for _ , n := range nodes {
latency := n .Latency ()
if closestNode == nil || latency < minLatency {
closestNode = n
minLatency = latency
}
if !n .Failing () && (closestNonFailingNode == nil || latency < minNonFailingLatency ) {
closestNonFailingNode = n
minNonFailingLatency = latency
allNodesFailing = false
}
}
if !allNodesFailing && closestNonFailingNode != nil {
return closestNonFailingNode , nil
}
if minLatency < maximumNodeLatency && closestNode != nil {
internal .Logger .Printf (context .TODO (), "redis: all nodes are marked as failed, picking the temporarily failing node with lowest latency" )
return closestNode , nil
}
internal .Logger .Printf (context .TODO (), "redis: pings to all nodes are failing, picking a random node across the cluster" )
return c .nodes .Random ()
}
func (c *clusterState ) slotNodeWithinLatency (slot int , tolerance time .Duration ) (*clusterNode , error ) {
entry := c .slotEntry (slot )
if entry == nil || len (entry .nodes ) == 0 {
return c .nodes .Random ()
}
nodes := entry .nodes
type sample struct {
node *clusterNode
latency time .Duration
}
var (
healthy = make ([]sample , 0 , len (nodes ))
closestNode *clusterNode
closestHealthyNode *clusterNode
minLatency = time .Duration (math .MaxInt64 )
minHealthyLatency = time .Duration (math .MaxInt64 )
anyHealthyMeasured bool
)
for _ , n := range nodes {
latency := n .Latency ()
if latency < minLatency {
closestNode , minLatency = n , latency
}
if n .Failing () {
continue
}
healthy = append (healthy , sample {node : n , latency : latency })
if latency != unmeasuredNodeLatency {
anyHealthyMeasured = true
}
if latency < minHealthyLatency {
closestHealthyNode , minHealthyLatency = n , latency
}
}
if closestHealthyNode != nil {
if !anyHealthyMeasured {
return closestHealthyNode , nil
}
candidates := make ([]*clusterNode , 0 , len (healthy ))
for _ , s := range healthy {
if s .latency -minHealthyLatency <= tolerance {
candidates = append (candidates , s .node )
}
}
ready := candidates [:0 ]
for _ , n := range candidates {
if !n .Loading () {
ready = append (ready , n )
}
}
if len (ready ) == 0 {
var (
fallback *clusterNode
fallbackLatency = time .Duration (math .MaxInt64 )
)
for _ , s := range healthy {
if s .latency -minHealthyLatency <= tolerance {
continue
}
if s .latency < fallbackLatency && !s .node .Loading () {
fallback , fallbackLatency = s .node , s .latency
}
}
if fallback != nil {
return fallback , nil
}
return closestHealthyNode , nil
}
if len (ready ) == 1 {
return ready [0 ], nil
}
return ready [(entry .latencyBandNodeCursor .Add (1 )-1 )%uint32 (len (ready ))], nil
}
if minLatency < maximumNodeLatency && closestNode != nil {
internal .Logger .Printf (context .TODO (), "redis: all nodes are marked as failed, picking the temporarily failing node with lowest latency" )
return closestNode , nil
}
internal .Logger .Printf (context .TODO (), "redis: pings to all nodes are failing, picking a random node across the cluster" )
return c .nodes .Random ()
}
func (c *clusterState ) slotRandomNode (slot int ) (*clusterNode , error ) {
nodes := c .slotNodes (slot )
if len (nodes ) == 0 {
return c .nodes .Random ()
}
if len (nodes ) == 1 {
return nodes [0 ], nil
}
randomNodes := rand .Perm (len (nodes ))
for _ , idx := range randomNodes {
if node := nodes [idx ]; !node .Failing () {
return node , nil
}
}
return nodes [randomNodes [0 ]], nil
}
func (c *clusterState ) slotShardPickerSlaveNode (slot int , shardPicker routing .ShardPicker ) (*clusterNode , error ) {
nodes := c .slotNodes (slot )
if len (nodes ) == 0 {
return c .nodes .Random ()
}
slaves := nodes [1 :]
if len (slaves ) > 0 {
for i := 0 ; i < len (slaves ); i ++ {
idx := shardPicker .Next (len (slaves ))
slave := slaves [idx ]
if !slave .Failing () && !slave .Loading () {
return slave , nil
}
}
}
return nodes [0 ], nil
}
func (c *clusterState ) slotEntry (slot int ) *clusterSlot {
i := sort .Search (len (c .slots ), func (i int ) bool {
return c .slots [i ].end >= slot
})
if i >= len (c .slots ) {
return nil
}
x := c .slots [i ]
if slot >= x .start && slot <= x .end {
return x
}
return nil
}
func (c *clusterState ) slotNodes (slot int ) []*clusterNode {
if x := c .slotEntry (slot ); x != nil {
return x .nodes
}
return nil
}
type clusterStateHolder struct {
load func (ctx context .Context ) (*clusterState , error )
reloadInterval time .Duration
state atomic .Value
reloading atomic .Uint32
reloadPending atomic .Uint32
}
func newClusterStateHolder(load func (ctx context .Context ) (*clusterState , error ), reloadInterval time .Duration ) *clusterStateHolder {
return &clusterStateHolder {
load : load ,
reloadInterval : reloadInterval ,
}
}
func (c *clusterStateHolder ) Reload (ctx context .Context ) (*clusterState , error ) {
state , err := c .load (ctx )
if err != nil {
return nil , err
}
c .state .Store (state )
return state , nil
}
func (c *clusterStateHolder ) LazyReload () {
if !c .reloading .CompareAndSwap (0 , 1 ) {
c .reloadPending .Store (1 )
return
}
go func () {
for {
_ , err := c .Reload (context .Background ())
if err != nil {
c .reloadPending .Store (0 )
c .reloading .Store (0 )
return
}
c .reloadPending .Store (0 )
time .Sleep (200 * time .Millisecond )
if c .reloadPending .Load () == 0 {
c .reloading .Store (0 )
return
}
}
}()
}
func (c *clusterStateHolder ) Get (ctx context .Context ) (*clusterState , error ) {
v := c .state .Load ()
if v == nil {
return c .Reload (ctx )
}
state := v .(*clusterState )
if time .Since (state .createdAt ) > c .reloadInterval {
c .LazyReload ()
}
return state , nil
}
func (c *clusterStateHolder ) ReloadOrGet (ctx context .Context ) (*clusterState , error ) {
state , err := c .Reload (ctx )
if err == nil {
return state , nil
}
return c .Get (ctx )
}
type ClusterClient struct {
opt *ClusterOptions
nodes *clusterNodes
state *clusterStateHolder
cmdsInfoCache *cmdsInfoCache
cmdInfoResolver *commandInfoResolver
cmdable
hooksMixin
himport *himportRegistry
autopipelinerMu *sync .Mutex
autopipeliner *AutoPipeliner
asyncAutopipeliner *AutoPipeliner
autopipelinerClosed bool
}
func NewClusterClient (opt *ClusterOptions ) *ClusterClient {
if opt == nil {
panic ("redis: NewClusterClient nil options" )
}
opt .init ()
c := &ClusterClient {
opt : opt ,
nodes : newClusterNodes (opt ),
himport : newHImportRegistry (),
autopipelinerMu : &sync .Mutex {},
}
c .nodes .OnNewNode (func (nodeClient *Client ) {
nodeClient .himport = c .himport
})
c .cmdsInfoCache = newCmdsInfoCache (c .cmdsInfo )
c .state = newClusterStateHolder (c .loadState , opt .ClusterStateReloadInterval )
c .SetCommandInfoResolver (NewDefaultCommandPolicyResolver ())
c .cmdable = c .Process
c .initHooks (hooks {
dial : nil ,
process : c .process ,
pipeline : c .processPipeline ,
txPipeline : c .processTxPipeline ,
})
if opt .MaintNotificationsConfig != nil {
c .nodes .OnNewNode (func (nodeClient *Client ) {
manager := nodeClient .GetMaintNotificationsManager ()
if manager != nil {
manager .SetClusterStateReloadCallback (func (ctx context .Context , hostPort string , slotRanges []string ) {
if internal .LogLevel .InfoOrAbove () {
internal .Logger .Printf (ctx , "cluster: slots %v migrated to %s, reloading cluster state" , slotRanges , hostPort )
}
c .state .LazyReload ()
})
}
})
}
return c
}
func (c *ClusterClient ) Options () *ClusterOptions {
return c .opt
}
func (c *ClusterClient ) ReloadState (ctx context .Context ) {
c .state .LazyReload ()
}
func (c *ClusterClient ) Close () error {
c .autopipelinerMu .Lock ()
ap , async := c .autopipeliner , c .asyncAutopipeliner
c .autopipeliner , c .asyncAutopipeliner = nil , nil
c .autopipelinerClosed = true
c .autopipelinerMu .Unlock ()
var firstErr error
for _ , p := range []*AutoPipeliner {ap , async } {
if p != nil {
if err := p .Close (); err != nil && firstErr == nil {
firstErr = err
}
}
}
if err := c .nodes .Close (); err != nil && firstErr == nil {
firstErr = err
}
return firstErr
}
func (c *ClusterClient ) Process (ctx context .Context , cmd Cmder ) error {
err := c .processHook (ctx , cmd )
cmd .SetErr (err )
return err
}
func (c *ClusterClient ) process (ctx context .Context , cmd Cmder ) error {
slot := c .cmdSlot (cmd , -1 )
var node *clusterNode
var moved bool
var ask bool
var lastErr error
for attempt := 0 ; attempt <= c .opt .MaxRedirects ; attempt ++ {
if attempt > 0 && !moved && !ask {
if err := internal .Sleep (ctx , c .retryBackoff (attempt )); err != nil {
return err
}
}
if node == nil {
var err error
if !c .opt .DisableRoutingPolicies && c .opt .ShardPicker != nil {
node , err = c .cmdNodeWithShardPicker (ctx , cmd .Name (), slot , c .opt .ShardPicker )
} else {
node , err = c .cmdNode (ctx , cmd .Name (), slot )
}
if err != nil {
return err
}
}
if ask {
ask = false
pipe := node .Client .Pipeline ()
_ = pipe .Process (ctx , NewCmd (ctx , "asking" ))
_ = pipe .Process (ctx , cmd )
_, lastErr = pipe .Exec (ctx )
} else {
if !c .opt .DisableRoutingPolicies {
lastErr = c .routeAndRun (ctx , cmd , node )
} else {
lastErr = node .Client .Process (ctx , cmd )
}
}
if lastErr == nil {
return nil
}
if isReadOnly := isReadOnlyError (lastErr ); isReadOnly || lastErr == pool .ErrClosed {
if isReadOnly {
c .state .LazyReload ()
}
node = nil
continue
}
if c .opt .ReadOnly && isLoadingError (lastErr ) {
node .MarkAsFailing ()
node = nil
continue
}
var addr string
moved , ask , addr = isMovedError (lastErr )
if moved || ask {
c .state .LazyReload ()
if errorCallback := pool .GetMetricErrorCallback (); errorCallback != nil {
errorType := "MOVED"
statusCode := "MOVED"
if ask {
errorType = "ASK"
statusCode = "ASK"
}
errorCallback (ctx , errorType , nil , statusCode , false , 0 )
}
var err error
node , err = c .nodes .GetOrCreate (addr )
if err != nil {
return err
}
continue
}
if shouldRetry (lastErr , cmd .readTimeout () == nil ) && !cmd .NoRetry () {
if attempt == 0 {
continue
}
node .MarkAsFailing ()
node = nil
continue
}
return lastErr
}
return lastErr
}
func (c *ClusterClient ) OnNewNode (fn func (rdb *Client )) {
c .nodes .OnNewNode (fn )
}
func (c *ClusterClient ) ForEachMaster (
ctx context .Context ,
fn func (ctx context .Context , client *Client ) error ,
) error {
state , err := c .state .ReloadOrGet (ctx )
if err != nil {
return err
}
var wg sync .WaitGroup
errCh := make (chan error , 1 )
for _ , master := range state .Masters {
wg .Add (1 )
go func (node *clusterNode ) {
defer wg .Done ()
err := fn (ctx , node .Client )
if err != nil {
select {
case errCh <- err :
default :
}
}
}(master )
}
wg .Wait ()
select {
case err := <- errCh :
return err
default :
return nil
}
}
func (c *ClusterClient ) ForEachSlave (
ctx context .Context ,
fn func (ctx context .Context , client *Client ) error ,
) error {
state , err := c .state .ReloadOrGet (ctx )
if err != nil {
return err
}
var wg sync .WaitGroup
errCh := make (chan error , 1 )
for _ , slave := range state .Slaves {
wg .Add (1 )
go func (node *clusterNode ) {
defer wg .Done ()
err := fn (ctx , node .Client )
if err != nil {
select {
case errCh <- err :
default :
}
}
}(slave )
}
wg .Wait ()
select {
case err := <- errCh :
return err
default :
return nil
}
}
func (c *ClusterClient ) ForEachShard (
ctx context .Context ,
fn func (ctx context .Context , client *Client ) error ,
) error {
state , err := c .state .ReloadOrGet (ctx )
if err != nil {
return err
}
var wg sync .WaitGroup
errCh := make (chan error , 1 )
worker := func (node *clusterNode ) {
defer wg .Done ()
err := fn (ctx , node .Client )
if err != nil {
select {
case errCh <- err :
default :
}
}
}
for _ , node := range state .Masters {
wg .Add (1 )
go worker (node )
}
for _ , node := range state .Slaves {
wg .Add (1 )
go worker (node )
}
wg .Wait ()
select {
case err := <- errCh :
return err
default :
return nil
}
}
func (c *ClusterClient ) PoolStats () *PoolStats {
var acc PoolStats
var pipe pool .Stats
havePipe := false
state , _ := c .state .Get (context .TODO ())
if state == nil {
return &acc
}
foldNode := func (client *Client ) {
s := client .connPool .Stats ()
acc .Hits += s .Hits
acc .Misses += s .Misses
acc .Timeouts += s .Timeouts
acc .WaitCount += s .WaitCount
acc .WaitDurationNs += s .WaitDurationNs
acc .TotalConns += s .TotalConns
acc .IdleConns += s .IdleConns
acc .StaleConns += s .StaleConns
if pp := client .getPipelinePool (); pp != nil {
ps := pp .Stats ()
pipe .Hits += ps .Hits
pipe .Misses += ps .Misses
pipe .Timeouts += ps .Timeouts
pipe .WaitCount += ps .WaitCount
pipe .WaitDurationNs += ps .WaitDurationNs
pipe .TotalConns += ps .TotalConns
pipe .IdleConns += ps .IdleConns
pipe .StaleConns += ps .StaleConns
havePipe = true
}
}
for _ , node := range state .Masters {
foldNode (node .Client )
}
for _ , node := range state .Slaves {
foldNode (node .Client )
}
if havePipe {
acc .PipelineStats = &pipe
}
return &acc
}
func (c *ClusterClient ) loadState (ctx context .Context ) (*clusterState , error ) {
if c .opt .ClusterSlots != nil {
slots , err := c .opt .ClusterSlots (ctx )
if err != nil {
return nil , err
}
return newClusterState (c .nodes , slots , "" )
}
addrs , err := c .nodes .Addrs ()
if err != nil {
return nil , err
}
var firstErr error
for _ , idx := range rand .Perm (len (addrs )) {
addr := addrs [idx ]
node , err := c .nodes .GetOrCreate (addr )
if err != nil {
if firstErr == nil {
firstErr = err
}
continue
}
slots , err := node .Client .ClusterSlots (ctx ).Result ()
if err != nil {
if firstErr == nil {
firstErr = err
}
continue
}
return newClusterState (c .nodes , slots , addr )
}
c .nodes .mu .Lock ()
c .nodes .activeAddrs = nil
c .nodes .mu .Unlock ()
return nil , firstErr
}
func (c *ClusterClient ) Pipeline () Pipeliner {
pipe := Pipeline {
exec : pipelineExecer (c .processPipelineHook ),
}
pipe .init ()
return &pipe
}
func clusterAutoPipelineOptions(cfg *AutoPipelineOptions ) *AutoPipelineOptions {
c2 := *cfg
if c2 .NumShards == 0 {
c2 .NumShards = numAutoPipelineShards ()
}
c2 .contentSharded = true
return &c2
}
func (c *ClusterClient ) AutoPipeline () (*AutoPipeliner , error ) {
return c .AutoPipelineWithOptions (nil )
}
func (c *ClusterClient ) AutoPipelineWithOptions (config *AutoPipelineOptions ) (*AutoPipeliner , error ) {
return getOrCreateAutoPipeliner (c .autopipelinerMu , &c .autopipeliner , &c .autopipelinerClosed , nil , nil , "" , config ,
func () *AutoPipelineOptions {
if c .opt .AutoPipelineOptions != nil {
return c .opt .AutoPipelineOptions
}
return DefaultBlockingAutoPipelineOptions ()
},
func (cfg *AutoPipelineOptions ) (*AutoPipeliner , error ) {
ap , err := newAutoPipeliner (c , clusterAutoPipelineOptions (cfg ), true )
if err != nil {
return nil , err
}
c .installAutoPipelineSharding (ap )
return ap , nil
})
}
func (c *ClusterClient ) installAutoPipelineSharding (ap *AutoPipeliner ) {
ap .setPreflight (func (ctx context .Context , cmd Cmder ) error {
if c .cmdInfoResolver == nil {
return nil
}
if policy := c .cmdInfoResolver .GetCommandPolicy (ctx , cmd ); policy != nil && !policy .CanBeUsedInPipeline () {
return fmt .Errorf (
"redis: cannot pipeline command %q with request policy ReqAllNodes/ReqAllShards/ReqMultiShard; Note: This behavior is subject to change in the future" , cmd .Name (),
)
}
return nil
})
ap .setMustDivert (func (ctx context .Context , cmd Cmder ) bool {
if c .cmdInfoResolver == nil {
return false
}
policy := c .cmdInfoResolver .GetCommandPolicy (ctx , cmd )
return policy != nil && policy .Request == routing .ReqSpecial
})
const slots = 16384
n := ap .numShards ()
ap .setShardFn (func (cmd Cmder ) int {
slot := c .cmdSlot (cmd , -1 )
if slot < 0 {
return 0
}
return slot * n / slots
})
}
func (c *ClusterClient ) AsyncAutoPipeline () (*AutoPipeliner , error ) {
return c .AsyncAutoPipelineWithOptions (nil )
}
func (c *ClusterClient ) AsyncAutoPipelineWithOptions (config *AutoPipelineOptions ) (*AutoPipeliner , error ) {
return getOrCreateAutoPipeliner (c .autopipelinerMu , &c .asyncAutopipeliner , &c .autopipelinerClosed , nil , nil , "" , config ,
func () *AutoPipelineOptions {
if c .opt .AutoPipelineOptions != nil {
return c .opt .AutoPipelineOptions
}
return DefaultAutoPipelineOptions ()
},
func (cfg *AutoPipelineOptions ) (*AutoPipeliner , error ) {
ap , err := newAutoPipeliner (c , clusterAutoPipelineOptions (cfg ), false )
if err != nil {
return nil , err
}
c .installAutoPipelineSharding (ap )
return ap , nil
})
}
func (c *ClusterClient ) Pipelined (ctx context .Context , fn func (Pipeliner ) error ) ([]Cmder , error ) {
return c .Pipeline ().Pipelined (ctx , fn )
}
func (c *ClusterClient ) processPipeline (ctx context .Context , cmds []Cmder ) error {
var operationStart time .Time
pipelineOpDurationCallback := otel .GetPipelineOperationDurationCallback ()
if pipelineOpDurationCallback != nil {
operationStart = time .Now ()
}
totalAttempts := 0
cmdsMap := newCmdsMap ()
if err := c .mapCmdsByNode (ctx , cmdsMap , cmds ); err != nil {
setCmdsErr (cmds , err )
if pipelineOpDurationCallback != nil {
operationDuration := time .Since (operationStart )
pipelineOpDurationCallback (ctx , operationDuration , "PIPELINE" , len (cmds ), 1 , err , nil , 0 )
}
return err
}
var lastErr error
for attempt := 0 ; attempt <= c .opt .MaxRedirects ; attempt ++ {
totalAttempts ++
if attempt > 0 {
if err := internal .Sleep (ctx , c .retryBackoff (attempt )); err != nil {
setCmdsErr (cmds , err )
if pipelineOpDurationCallback != nil {
operationDuration := time .Since (operationStart )
pipelineOpDurationCallback (ctx , operationDuration , "PIPELINE" , len (cmds ), totalAttempts , err , nil , 0 )
}
return err
}
}
failedCmds := newCmdsMap ()
var wg sync .WaitGroup
for node , cmds := range cmdsMap .m {
wg .Add (1 )
go func (node *clusterNode , cmds []Cmder ) {
defer wg .Done ()
c .processPipelineNode (ctx , node , cmds , failedCmds )
}(node , cmds )
}
wg .Wait ()
if len (failedCmds .m ) == 0 {
break
}
cmdsMap = failedCmds
lastErr = cmdsFirstErr (cmds )
}
if pipelineOpDurationCallback != nil {
operationDuration := time .Since (operationStart )
finalErr := cmdsFirstErr (cmds )
if finalErr == nil {
finalErr = lastErr
}
pipelineOpDurationCallback (ctx , operationDuration , "PIPELINE" , len (cmds ), totalAttempts , finalErr , nil , 0 )
}
return cmdsFirstErr (cmds )
}
func (c *ClusterClient ) mapCmdsByNode (ctx context .Context , cmdsMap *cmdsMap , cmds []Cmder ) error {
state , err := c .state .Get (ctx )
if err != nil {
return err
}
if c .opt .ReadOnly && c .cmdsAreReadOnly (ctx , cmds ) {
for _ , cmd := range cmds {
var policy *routing .CommandPolicy
if c .cmdInfoResolver != nil {
policy = c .cmdInfoResolver .GetCommandPolicy (ctx , cmd )
}
if policy != nil && !policy .CanBeUsedInPipeline () {
err := fmt .Errorf (
"redis: cannot pipeline command %q with request policy ReqAllNodes/ReqAllShards/ReqMultiShard; Note: This behavior is subject to change in the future" , cmd .Name (),
)
setCmdsErr (cmds , err )
return err
}
slot := c .cmdSlot (cmd , -1 )
var node *clusterNode
if slot == -1 && !c .opt .DisableRoutingPolicies && c .opt .ShardPicker != nil {
if len (state .Masters ) == 0 {
return errClusterNoNodes
}
idx := c .opt .ShardPicker .Next (len (state .Masters ) + len (state .Slaves ))
if idx < len (state .Masters ) {
node = state .Masters [idx ]
} else {
node = state .Slaves [idx -len (state .Masters )]
}
} else {
node , err = c .slotReadOnlyNode (state , slot )
if err != nil {
return err
}
}
cmdsMap .Add (node , cmd )
}
return nil
}
for _ , cmd := range cmds {
var policy *routing .CommandPolicy
if c .cmdInfoResolver != nil {
policy = c .cmdInfoResolver .GetCommandPolicy (ctx , cmd )
}
if policy != nil && !policy .CanBeUsedInPipeline () {
err := fmt .Errorf (
"redis: cannot pipeline command %q with request policy ReqAllNodes/ReqAllShards/ReqMultiShard; Note: This behavior is subject to change in the future" , cmd .Name (),
)
setCmdsErr (cmds , err )
return err
}
slot := c .cmdSlot (cmd , -1 )
var node *clusterNode
if slot == -1 && !c .opt .DisableRoutingPolicies && c .opt .ShardPicker != nil {
if len (state .Masters ) == 0 {
return errClusterNoNodes
}
idx := c .opt .ShardPicker .Next (len (state .Masters ))
node = state .Masters [idx ]
} else {
node , err = state .slotMasterNode (slot )
if err != nil {
return err
}
}
cmdsMap .Add (node , cmd )
}
return nil
}
func (c *ClusterClient ) cmdsAreReadOnly (ctx context .Context , cmds []Cmder ) bool {
for _ , cmd := range cmds {
cmdInfo := c .cmdInfo (ctx , cmd .Name ())
if cmdInfo == nil || !cmdInfo .ReadOnly {
return false
}
}
return true
}
func (c *ClusterClient ) processPipelineNode (
ctx context .Context , node *clusterNode , cmds []Cmder , failedCmds *cmdsMap ,
) {
unregister := registerBatchExecutors (cmds )
defer unregister ()
executed := false
err := node .Client .withProcessPipelineHook (ctx , cmds , func (ctx context .Context , cmds []Cmder ) error {
executed = true
entered := false
err := node .Client .withPipelineConn (ctx , func (ctx context .Context , cn *pool .Conn ) error {
entered = true
return c .processPipelineNodeConn (ctx , node , cn , cmds , failedCmds )
})
if err != nil && !entered {
if !isContextError (err ) {
node .MarkAsFailing ()
}
_ = c .mapCmdsByNode (ctx , failedCmds , cmds )
setCmdsErr (cmds , err )
}
return err
})
if !executed {
setCmdsErr (cmds , err )
return
}
if err != nil && cmdsFirstErr (cmds ) == nil {
setCmdsErr (cmds , err )
}
}
func (c *ClusterClient ) processPipelineNodeConn (
ctx context .Context , node *clusterNode , cn *pool .Conn , cmds []Cmder , failedCmds *cmdsMap ,
) error {
injected := node .Client .himportInjectedCmds (ctx , cn , cmds )
if err := cn .WithWriter (c .context (ctx ), c .opt .WriteTimeout , func (wr *proto .Writer ) error {
for _ , ic := range injected {
if err := writeCmd (wr , ic ); err != nil {
return err
}
}
return writeCmds (wr , cmds )
}); err != nil {
if isBadConn (err , false , node .Client .getAddr ()) {
node .MarkAsFailing ()
}
if shouldRetry (err , true ) && !cmdsContainNoRetry (cmds ) {
_ = c .mapCmdsByNode (ctx , failedCmds , cmds )
}
setCmdsErr (cmds , err )
return err
}
return cn .WithReader (c .context (ctx ), c .opt .ReadTimeout , func (rd *proto .Reader ) error {
if err := node .Client .himportReadInjectedReplies (ctx , cn , rd , injected ); err != nil {
if isBadConn (err , false , node .Client .getAddr ()) {
node .MarkAsFailing ()
}
if shouldRetry (err , true ) && !cmdsContainNoRetry (cmds ) {
_ = c .mapCmdsByNode (ctx , failedCmds , cmds )
}
setCmdsErr (cmds , err )
return err
}
err := c .pipelineReadCmds (ctx , node , cn , rd , cmds , failedCmds )
if err == nil || isRedisError (err ) {
node .Client .himportAfterBatch (cn , injected , cmds )
if err == nil {
c .himportRequeueFailedSets (ctx , cmds , failedCmds )
}
}
return err
})
}
func (c *ClusterClient ) pipelineReadCmds (
ctx context .Context ,
node *clusterNode ,
cn *pool .Conn ,
rd *proto .Reader ,
cmds []Cmder ,
failedCmds *cmdsMap ,
) error {
for i , cmd := range cmds {
if err := node .Client .processPendingPushNotificationWithReader (ctx , cn , rd ); err != nil {
internal .Logger .Printf (ctx , "push: error processing pending notifications before reading reply: %v" , err )
}
err := cmd .readReply (rd )
cmd .SetErr (err )
if err == nil {
continue
}
if c .checkMovedErr (ctx , cmd , err , failedCmds ) {
continue
}
if c .opt .ReadOnly && isBadConn (err , false , node .Client .getAddr ()) {
node .MarkAsFailing ()
}
if !isRedisError (err ) {
if shouldRetry (err , true ) && !cmdsContainNoRetry (cmds ) {
_ = c .mapCmdsByNode (ctx , failedCmds , cmds )
}
setCmdsErr (cmds [i +1 :], err )
return err
}
}
if err := cmds [0 ].rawErr (); err != nil && shouldRetry (err , true ) && !cmdsContainNoRetry (cmds ) {
_ = c .mapCmdsByNode (ctx , failedCmds , cmds )
return err
}
return nil
}
func (c *ClusterClient ) checkMovedErr (
ctx context .Context , cmd Cmder , err error , failedCmds *cmdsMap ,
) bool {
moved , ask , addr := isMovedError (err )
if !moved && !ask {
return false
}
node , err := c .nodes .GetOrCreate (addr )
if err != nil {
return false
}
if moved {
c .state .LazyReload ()
failedCmds .Add (node , cmd )
return true
}
if ask {
failedCmds .Add (node , NewCmd (ctx , "asking" ), cmd )
return true
}
panic ("not reached" )
}
func (c *ClusterClient ) TxPipeline () Pipeliner {
pipe := Pipeline {
exec : func (ctx context .Context , cmds []Cmder ) error {
cmds = wrapMultiExec (ctx , cmds )
return c .processTxPipelineHook (ctx , cmds )
},
}
pipe .init ()
return &pipe
}
func (c *ClusterClient ) TxPipelined (ctx context .Context , fn func (Pipeliner ) error ) ([]Cmder , error ) {
return c .TxPipeline ().Pipelined (ctx , fn )
}
type txOutcomeKind int
const (
txSuccess txOutcomeKind = iota
txRetryMoved
txRetryAsk
txRetryTryAgain
txRetryConn
txFatal
)
type txOutcome struct {
kind txOutcomeKind
err error
addr string
execErr error
unreadReplies bool
}
type txRedirect struct {
moved bool
ask bool
tryAgain bool
addr string
err error
}
var errTxDirtyConn = errors .New ("redis: connection has unread transaction replies" )
func (c *ClusterClient ) processTxPipeline (ctx context .Context , cmds []Cmder ) (retErr error ) {
var operationStart time .Time
pipelineOpDurationCallback := otel .GetPipelineOperationDurationCallback ()
if pipelineOpDurationCallback != nil {
operationStart = time .Now ()
}
totalAttempts := 0
var lastErr error
defer func () {
if pipelineOpDurationCallback == nil {
return
}
finalErr := cmp .Or (retErr , cmdsFirstErr (cmds ), lastErr )
pipelineOpDurationCallback (ctx , time .Since (operationStart ), "MULTI" , len (cmds ), totalAttempts , finalErr , nil , 0 )
}()
cmds = cmds [1 : len (cmds )-1 ]
if len (cmds ) == 0 {
return nil
}
state , err := c .state .Get (ctx )
if err != nil {
setCmdsErr (cmds , err )
return err
}
keyedCmdsBySlot := c .slottedKeyedCommands (ctx , cmds )
slot := -1
switch len (keyedCmdsBySlot ) {
case 0 :
slot = hashtag .RandomSlot ()
case 1 :
for sl := range keyedCmdsBySlot {
slot = sl
}
default :
setCmdsErr (cmds , ErrCrossSlot )
return ErrCrossSlot
}
node , err := state .slotMasterNode (slot )
if err != nil {
setCmdsErr (cmds , err )
return err
}
asking := false
redirected := false
for attempt := 0 ; attempt <= c .opt .MaxRedirects ; attempt ++ {
totalAttempts ++
if attempt > 0 && !redirected {
if err := internal .Sleep (ctx , c .retryBackoff (attempt )); err != nil {
setCmdsErr (cmds , err )
return err
}
}
outcome := c .processTxPipelineNode (ctx , node , cmds , asking )
lastErr = outcome .err
redirected = false
switch outcome .kind {
case txSuccess :
return cmdsFirstErr (cmds )
case txRetryMoved :
redirected = true
asking = false
c .state .LazyReload ()
if node , err = c .nodes .GetOrCreate (outcome .addr ); err != nil {
setCmdsErr (cmds , err )
return err
}
case txRetryAsk :
redirected = true
asking = true
if node , err = c .nodes .GetOrCreate (outcome .addr ); err != nil {
setCmdsErr (cmds , err )
return err
}
case txRetryTryAgain , txRetryConn :
case txFatal :
abortErr := cmp .Or (outcome .execErr , outcome .err )
for _ , cmd := range cmds {
if cmd .Err () == nil {
cmd .SetErr (abortErr )
}
}
return lastErr
}
}
if lastErr != nil {
setCmdsErr (cmds , lastErr )
}
return cmdsFirstErr (cmds )
}
func (c *ClusterClient ) slottedKeyedCommands (_ context .Context , cmds []Cmder ) map [int ][]Cmder {
cmdsSlots := map [int ][]Cmder {}
cachedInfo := c .cmdsInfoCache .Peek ()
prefferedRandomSlot := -1
for _ , cmd := range cmds {
var info *CommandInfo
if cachedInfo != nil {
info = cachedInfo [cmd .Name ()]
}
pos := cmdFirstKeyPosWithInfo (cmd , info )
if pos == 0 {
continue
}
slot := c .cmdSlotWithPos (cmd , pos , prefferedRandomSlot )
if prefferedRandomSlot == -1 {
prefferedRandomSlot = slot
}
cmdsSlots [slot ] = append (cmdsSlots [slot ], cmd )
}
return cmdsSlots
}
func (c *ClusterClient ) processTxPipelineNode (
ctx context .Context , node *clusterNode , cmds []Cmder , asking bool ,
) *txOutcome {
wire := wrapMultiExec (ctx , cmds )
if asking {
wire = append ([]Cmder {NewCmd (ctx , "asking" )}, wire ...)
}
var outcome *txOutcome
executed := false
chainErr := node .Client .withProcessPipelineHook (ctx , wire , func (ctx context .Context , wire []Cmder ) error {
executed = true
entered := false
err := node .Client .withPipelineConn (ctx , func (ctx context .Context , cn *pool .Conn ) error {
entered = true
outcome = c .processTxPipelineNodeConn (ctx , node , cn , wire , cmds , asking )
connErr := outcome .err
if isRedisError (outcome .err ) {
connErr = nil
}
if outcome .unreadReplies {
connErr = errTxDirtyConn
}
return connErr
})
if !entered && err != nil {
if shouldRetry (err , true ) && !cmdsContainNoRetry (cmds ) {
outcome = &txOutcome {kind : txRetryConn , err : err }
} else {
outcome = &txOutcome {kind : txFatal , err : err }
}
}
return err
})
if !executed && chainErr != nil {
outcome = &txOutcome {kind : txFatal , err : chainErr }
}
if outcome == nil {
outcome = &txOutcome {kind : txFatal , err : fmt .Errorf ("redis: tx pipeline produced no outcome" )}
}
return outcome
}
func (c *ClusterClient ) processTxPipelineNodeConn (
ctx context .Context , node *clusterNode , cn *pool .Conn , wire []Cmder , cmds []Cmder , asking bool ,
) *txOutcome {
injected := node .Client .himportInjectedCmds (ctx , cn , cmds )
if err := cn .WithWriter (c .context (ctx ), c .opt .WriteTimeout , func (wr *proto .Writer ) error {
for _ , ic := range injected {
if err := writeCmd (wr , ic ); err != nil {
return err
}
}
return writeCmds (wr , wire )
}); err != nil {
if shouldRetry (err , true ) && !cmdsContainNoRetry (cmds ) {
return &txOutcome {kind : txRetryConn , err : err }
}
return &txOutcome {kind : txFatal , err : err }
}
var outcome *txOutcome
readErr := cn .WithReader (c .context (ctx ), c .opt .ReadTimeout , func (rd *proto .Reader ) error {
if err := node .Client .himportReadInjectedReplies (ctx , cn , rd , injected ); err != nil {
outcome = c .txReadFatal (err )
return nil
}
outcome = c .readTxPipelineReplies (ctx , node , cn , rd , cmds , asking )
if outcome != nil && outcome .kind == txSuccess {
node .Client .himportAfterBatch (cn , injected , cmds )
}
return nil
})
if readErr != nil {
return c .txReadFatal (readErr )
}
return outcome
}
func (c *ClusterClient ) readTxPipelineReplies (
ctx context .Context , node *clusterNode , cn *pool .Conn , rd *proto .Reader , cmds []Cmder , asking bool ,
) *txOutcome {
scratch := NewStatusCmd (ctx )
readStatus := func () error {
c .txProcessPush (ctx , node , cn , rd )
return scratch .readReply (rd )
}
if asking {
if err := readStatus (); err != nil {
return c .txPreQueueErrorOutcome (err , cmds )
}
}
if err := readStatus (); err != nil {
return c .txPreQueueErrorOutcome (err , cmds )
}
var firstRedirect *txRedirect
var firstFatal error
for _ , cmd := range cmds {
err := readStatus ()
if err == nil {
continue
}
if !isRedisError (err ) {
return c .txReadFatal (err )
}
if moved , ask , addr := isMovedError (err ); moved || ask {
if firstRedirect == nil {
firstRedirect = &txRedirect {moved : moved , ask : ask , addr : addr , err : err }
}
continue
}
if proto .IsTryAgainError (err ) {
if firstRedirect == nil {
firstRedirect = &txRedirect {tryAgain : true , err : err }
}
continue
}
cmd .SetErr (err )
if firstFatal == nil {
firstFatal = err
}
}
c .txProcessPush (ctx , node , cn , rd )
line , err := rd .ReadLine ()
if err != nil {
if !isRedisError (err ) {
return c .txReadFatal (err )
}
return c .classifyExecError (err , firstRedirect , firstFatal )
}
if line [0 ] != proto .RespArray {
err := fmt .Errorf ("redis: unexpected EXEC reply %q" , line )
setCmdsErr (cmds , err )
return &txOutcome {kind : txFatal , err : err , unreadReplies : true }
}
if err := node .Client .pipelineReadCmds (ctx , cn , rd , cmds ); err != nil && !isRedisError (err ) {
return c .txReadFatal (err )
}
return &txOutcome {kind : txSuccess }
}
func (c *ClusterClient ) txProcessPush (ctx context .Context , node *clusterNode , cn *pool .Conn , rd *proto .Reader ) {
if err := node .Client .processPendingPushNotificationWithReader (ctx , cn , rd ); err != nil {
internal .Logger .Printf (ctx , "push: error processing pending notifications before reading reply: %v" , err )
}
}
func (c *ClusterClient ) txReadFatal (err error ) *txOutcome {
return &txOutcome {kind : txFatal , err : err , unreadReplies : true }
}
func (c *ClusterClient ) txPreQueueErrorOutcome (err error , cmds []Cmder ) *txOutcome {
if !isRedisError (err ) {
return c .txReadFatal (err )
}
if shouldRetry (err , true ) && !cmdsContainNoRetry (cmds ) {
return &txOutcome {kind : txRetryConn , err : err , unreadReplies : true }
}
return &txOutcome {kind : txFatal , err : err , unreadReplies : true }
}
func (c *ClusterClient ) classifyExecError (execErr error , firstRedirect *txRedirect , firstFatal error ) *txOutcome {
if moved , ask , addr := isMovedError (execErr ); moved || ask {
if ask {
return &txOutcome {kind : txRetryAsk , err : execErr , addr : addr }
}
return &txOutcome {kind : txRetryMoved , err : execErr , addr : addr }
}
if proto .IsTryAgainError (execErr ) {
return &txOutcome {kind : txRetryTryAgain , err : execErr }
}
if proto .IsClusterDownError (execErr ) {
return &txOutcome {kind : txRetryConn , err : execErr }
}
if proto .IsExecAbortError (execErr ) {
if firstFatal != nil {
return &txOutcome {kind : txFatal , err : firstFatal , execErr : execErr }
}
if firstRedirect != nil {
switch {
case firstRedirect .moved :
return &txOutcome {kind : txRetryMoved , err : firstRedirect .err , addr : firstRedirect .addr }
case firstRedirect .ask :
return &txOutcome {kind : txRetryAsk , err : firstRedirect .err , addr : firstRedirect .addr }
case firstRedirect .tryAgain :
return &txOutcome {kind : txRetryTryAgain , err : firstRedirect .err }
}
}
return &txOutcome {kind : txFatal , err : execErr , execErr : execErr }
}
return &txOutcome {kind : txFatal , err : execErr }
}
func (c *ClusterClient ) Watch (ctx context .Context , fn func (*Tx ) error , keys ...string ) error {
if len (keys ) == 0 {
return errNoWatchKeys
}
slot := hashtag .Slot (keys [0 ])
for _ , key := range keys [1 :] {
if hashtag .Slot (key ) != slot {
return errWatchCrosslot
}
}
node , err := c .slotMasterNode (ctx , slot )
if err != nil {
return err
}
for attempt := 0 ; attempt <= c .opt .MaxRedirects ; attempt ++ {
if attempt > 0 {
if err := internal .Sleep (ctx , c .retryBackoff (attempt )); err != nil {
return err
}
}
var fnErr error
err = node .Client .Watch (ctx , func (tx *Tx ) error {
fnErr = fn (tx )
return fnErr
}, keys ...)
if err == nil {
break
}
if fnErr != nil {
return fnErr
}
moved , ask , addr := isMovedError (err )
if moved || ask {
node , err = c .nodes .GetOrCreate (addr )
if err != nil {
return err
}
continue
}
if isReadOnly := isReadOnlyError (err ); isReadOnly || err == pool .ErrClosed {
if isReadOnly {
c .state .LazyReload ()
}
node , err = c .slotMasterNode (ctx , slot )
if err != nil {
return err
}
continue
}
if shouldRetry (err , true ) {
continue
}
return err
}
return err
}
func (c *ClusterClient ) pubSub () *PubSub {
var node *clusterNode
pubsub := &PubSub {
opt : c .opt .clientOptions (),
newConn : func (ctx context .Context , addr string , channels []string ) (*pool .Conn , error ) {
if node != nil {
panic ("node != nil" )
}
var err error
if len (channels ) > 0 {
slot := hashtag .Slot (channels [0 ])
if c .opt .ReadOnly {
state , err := c .state .Get (ctx )
if err != nil {
return nil , err
}
node , err = c .slotReadOnlyNode (state , slot )
if err != nil {
return nil , err
}
} else {
node , err = c .slotMasterNode (ctx , slot )
if err != nil {
return nil , err
}
}
} else {
node , err = c .nodes .Random ()
if err != nil {
return nil , err
}
}
cn , err := node .Client .pubSubPool .NewConn (ctx , node .Client .opt .Network , node .Client .opt .Addr , channels )
if err != nil {
node = nil
return nil , err
}
err = node .Client .initConn (ctx , cn )
if err != nil {
_ = cn .Close ()
node = nil
return nil , err
}
node .Client .pubSubPool .TrackConn (cn )
return cn , nil
},
closeConn : func (cn *pool .Conn ) error {
node .Client .pubSubPool .UntrackConn (cn )
err := cn .Close ()
node = nil
return err
},
}
pubsub .init ()
return pubsub
}
func (c *ClusterClient ) Subscribe (ctx context .Context , channels ...string ) *PubSub {
pubsub := c .pubSub ()
if len (channels ) > 0 {
_ = pubsub .Subscribe (ctx , channels ...)
}
return pubsub
}
func (c *ClusterClient ) PSubscribe (ctx context .Context , channels ...string ) *PubSub {
pubsub := c .pubSub ()
if len (channels ) > 0 {
_ = pubsub .PSubscribe (ctx , channels ...)
}
return pubsub
}
func (c *ClusterClient ) SSubscribe (ctx context .Context , channels ...string ) *PubSub {
pubsub := c .pubSub ()
if len (channels ) > 0 {
_ = pubsub .SSubscribe (ctx , channels ...)
}
return pubsub
}
func (c *ClusterClient ) retryBackoff (attempt int ) time .Duration {
return internal .RetryBackoff (attempt , c .opt .MinRetryBackoff , c .opt .MaxRetryBackoff )
}
func (c *ClusterClient ) cmdsInfo (ctx context .Context ) (map [string ]*CommandInfo , error ) {
const nodeLimit = 3
addrs , err := c .nodes .Addrs ()
if err != nil {
return nil , err
}
var firstErr error
perm := rand .Perm (len (addrs ))
if len (perm ) > nodeLimit {
perm = perm [:nodeLimit ]
}
for _ , idx := range perm {
addr := addrs [idx ]
node , err := c .nodes .GetOrCreate (addr )
if err != nil {
if firstErr == nil {
firstErr = err
}
continue
}
info , err := node .Client .Command (ctx ).Result ()
if err == nil {
return info , nil
}
if firstErr == nil {
firstErr = err
}
}
if firstErr == nil {
panic ("not reached" )
}
return nil , firstErr
}
func (c *ClusterClient ) cmdInfo (ctx context .Context , name string ) *CommandInfo {
cmdInfoCtx := c .context (ctx )
if c .opt .ContextTimeoutEnabled && ctx != nil {
var cancel context .CancelFunc
cmdInfoCtx , cancel = context .WithTimeout (context .Background (), 5 *time .Second )
defer cancel ()
}
cmdsInfo , err := c .cmdsInfoCache .Get (cmdInfoCtx )
if err != nil {
internal .Logger .Printf (cmdInfoCtx , "getting command info: %s" , err )
return nil
}
info := cmdsInfo [name ]
if info == nil {
internal .Logger .Printf (cmdInfoCtx , "info for cmd=%s not found" , name )
}
return info
}
func (c *ClusterClient ) cmdInfoPeek (name string ) *CommandInfo {
if cmds := c .cmdsInfoCache .Peek (); cmds != nil {
return cmds [name ]
}
return nil
}
func (c *ClusterClient ) cmdSlot (cmd Cmder , prefferedSlot int ) int {
if prefferedSlot == -1 {
if slot , ok := cmd .cachedSlot (); ok {
return slot
}
}
info := c .cmdInfoPeek (cmd .Name ())
slot := c .cmdSlotWithPos (cmd , cmdFirstKeyPosWithInfo (cmd , info ), prefferedSlot )
if prefferedSlot == -1 && slot >= 0 {
cmd .setCachedSlot (slot )
}
return slot
}
func (c *ClusterClient ) cmdSlotWithPos (cmd Cmder , pos int , prefferedSlot int ) int {
args := cmd .Args ()
if args [0 ] == "cluster" && (args [1 ] == "getkeysinslot" || args [1 ] == "countkeysinslot" ) {
return args [2 ].(int )
}
return cmdSlot (cmd , pos , prefferedSlot )
}
func cmdSlot(cmd Cmder , pos int , prefferedRandomSlot int ) int {
if pos == 0 {
if prefferedRandomSlot != -1 {
return prefferedRandomSlot
}
return -1
}
firstKey := cmd .stringArg (pos )
return hashtag .Slot (firstKey )
}
func (c *ClusterClient ) cmdNode (
ctx context .Context ,
cmdName string ,
slot int ,
) (*clusterNode , error ) {
state , err := c .state .Get (ctx )
if err != nil {
return nil , err
}
if c .opt .ReadOnly {
cmdInfo := c .cmdInfo (ctx , cmdName )
if cmdInfo != nil && cmdInfo .ReadOnly {
return c .slotReadOnlyNode (state , slot )
}
}
return state .slotMasterNode (slot )
}
func (c *ClusterClient ) cmdNodeWithShardPicker (
ctx context .Context ,
cmdName string ,
slot int ,
shardPicker routing .ShardPicker ,
) (*clusterNode , error ) {
state , err := c .state .Get (ctx )
if err != nil {
return nil , err
}
if slot == -1 {
if len (state .Masters ) == 0 {
return nil , errClusterNoNodes
}
idx := shardPicker .Next (len (state .Masters ))
return state .Masters [idx ], nil
}
if c .opt .ReadOnly {
cmdInfo := c .cmdInfo (ctx , cmdName )
if cmdInfo != nil && cmdInfo .ReadOnly {
return c .slotReadOnlyNode (state , slot )
}
}
return state .slotMasterNode (slot )
}
func (c *ClusterClient ) slotReadOnlyNode (state *clusterState , slot int ) (*clusterNode , error ) {
if c .opt .RouteByLatency {
if c .opt .RouteByLatencyTolerance > 0 {
return state .slotNodeWithinLatency (slot , c .opt .RouteByLatencyTolerance )
}
return state .slotClosestNode (slot )
}
if c .opt .RouteRandomly {
return state .slotRandomNode (slot )
}
if c .opt .ShardPicker != nil {
return state .slotShardPickerSlaveNode (slot , c .opt .ShardPicker )
}
return state .slotSlaveNode (slot )
}
func (c *ClusterClient ) slotMasterNode (ctx context .Context , slot int ) (*clusterNode , error ) {
state , err := c .state .Get (ctx )
if err != nil {
return nil , err
}
return state .slotMasterNode (slot )
}
func (c *ClusterClient ) SlaveForKey (ctx context .Context , key string ) (*Client , error ) {
state , err := c .state .Get (ctx )
if err != nil {
return nil , err
}
slot := hashtag .Slot (key )
node , err := c .slotReadOnlyNode (state , slot )
if err != nil {
return nil , err
}
return node .Client , err
}
func (c *ClusterClient ) MasterForKey (ctx context .Context , key string ) (*Client , error ) {
slot := hashtag .Slot (key )
node , err := c .slotMasterNode (ctx , slot )
if err != nil {
return nil , err
}
return node .Client , nil
}
func (c *ClusterClient ) context (ctx context .Context ) context .Context {
if c .opt .ContextTimeoutEnabled {
return ctx
}
return context .Background ()
}
func (c *ClusterClient ) GetResolver () *commandInfoResolver {
return c .cmdInfoResolver
}
func (c *ClusterClient ) SetCommandInfoResolver (cmdInfoResolver *commandInfoResolver ) {
c .cmdInfoResolver = cmdInfoResolver
}
func (c *ClusterClient ) extractCommandInfo (ctx context .Context , cmd Cmder ) *routing .CommandPolicy {
if cmdInfo := c .cmdInfo (ctx , cmd .Name ()); cmdInfo != nil && cmdInfo .CommandPolicy != nil {
return cmdInfo .CommandPolicy
}
return nil
}
func (c *ClusterClient ) NewDynamicResolver () *commandInfoResolver {
return &commandInfoResolver {
resolveFunc : c .extractCommandInfo ,
}
}
func appendIfNotExist[T comparable ](vals []T , newVal T ) []T {
if slices .Contains (vals , newVal ) {
return vals
}
return append (vals , newVal )
}
type cmdsMap struct {
mu sync .Mutex
m map [*clusterNode ][]Cmder
}
func newCmdsMap() *cmdsMap {
return &cmdsMap {
m : make (map [*clusterNode ][]Cmder ),
}
}
func (m *cmdsMap ) Add (node *clusterNode , cmds ...Cmder ) {
m .mu .Lock ()
m .m [node ] = append (m .m [node ], cmds ...)
m .mu .Unlock ()
}
The pages are generated with Golds v0.8.7 . (GOOS=linux GOARCH=amd64)
Golds is a Go 101 project developed by Tapir Liu .
PR and bug reports are welcome and can be submitted to the issue list .
Please follow @zigo_101 (reachable from the left QR code) to get the latest news of Golds .