Skip to content

Commit

Permalink
Merge pull request #540 from redis/fix-cluster-move-ipv6
Browse files Browse the repository at this point in the history
fix: ipv6 handling in MOVED and ASK messages of cluster mode
Signed-off-by: Rueian <[email protected]>
  • Loading branch information
rueian committed Apr 29, 2024
1 parent 2649a29 commit 83d4493
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 2 deletions.
14 changes: 12 additions & 2 deletions message.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"encoding/json"
"fmt"
"io"
"net"
"strconv"
"strings"
"time"
Expand Down Expand Up @@ -55,19 +56,28 @@ func (r *ValkeyError) IsNil() bool {
// IsMoved checks if it is a valkey MOVED message and returns moved address.
func (r *ValkeyError) IsMoved() (addr string, ok bool) {
if ok = strings.HasPrefix(r.string, "MOVED"); ok {
addr = strings.Split(r.string, " ")[2]
addr = fixIPv6HostPort(strings.Split(r.string, " ")[2])
}
return
}

// IsAsk checks if it is a valkey ASK message and returns ask address.
func (r *ValkeyError) IsAsk() (addr string, ok bool) {
if ok = strings.HasPrefix(r.string, "ASK"); ok {
addr = strings.Split(r.string, " ")[2]
addr = fixIPv6HostPort(strings.Split(r.string, " ")[2])
}
return
}

func fixIPv6HostPort(addr string) string {
if strings.IndexByte(addr, '.') < 0 && len(addr) > 0 && addr[0] != '[' { // skip ipv4 and enclosed ipv6
if i := strings.LastIndexByte(addr, ':'); i >= 0 {
return net.JoinHostPort(addr[:i], addr[i+1:])
}
}
return addr
}

// IsTryAgain checks if it is a valkey TRYAGAIN message and returns ask address.
func (r *ValkeyError) IsTryAgain() bool {
return strings.HasPrefix(r.string, "TRYAGAIN")
Expand Down
32 changes: 32 additions & 0 deletions message_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,38 @@ func TestIsValkeyErr(t *testing.T) {
}
}

func TestValkeyErrorIsMoved(t *testing.T) {
for _, c := range []struct {
err string
addr string
}{
{err: "MOVED 1 127.0.0.1:1", addr: "127.0.0.1:1"},
{err: "MOVED 1 [::1]:1", addr: "[::1]:1"},
{err: "MOVED 1 ::1:1", addr: "[::1]:1"},
} {
e := ValkeyError{typ: '-', string: c.err}
if addr, ok := e.IsMoved(); !ok || addr != c.addr {
t.Fail()
}
}
}

func TestValkeyErrorIsAsk(t *testing.T) {
for _, c := range []struct {
err string
addr string
}{
{err: "ASK 1 127.0.0.1:1", addr: "127.0.0.1:1"},
{err: "ASK 1 [::1]:1", addr: "[::1]:1"},
{err: "ASK 1 ::1:1", addr: "[::1]:1"},
} {
e := ValkeyError{typ: '-', string: c.err}
if addr, ok := e.IsAsk(); !ok || addr != c.addr {
t.Fail()
}
}
}

func TestIsValkeyBusyGroup(t *testing.T) {
err := errors.New("other")
if IsValkeyBusyGroup(err) {
Expand Down

0 comments on commit 83d4493

Please sign in to comment.