diff --git a/client.go b/client.go index 901718c..525061f 100644 --- a/client.go +++ b/client.go @@ -208,7 +208,9 @@ func (c *Client) do(key string, f func(*iopool.Buffer) error) error { } err = f(conn) - conn.SetHealth(err) + if !benign(err) { + conn.SetHealth(err) + } c.setConn(key, conn) return err } diff --git a/client_test.go b/client_test.go index 48c0e76..b353201 100644 --- a/client_test.go +++ b/client_test.go @@ -4,6 +4,8 @@ package memc import ( + "errors" + "io" "math" "strings" "testing" @@ -74,6 +76,43 @@ func Test_New_default_instance(t *testing.T) { }) } +func Test_benign(t *testing.T) { + t.Parallel() + + t.Run("nil", func(t *testing.T) { + must.True(t, benign(nil)) + }) + + t.Run("cache miss", func(t *testing.T) { + must.True(t, benign(ErrCacheMiss)) + }) + + t.Run("not stored", func(t *testing.T) { + must.True(t, benign(ErrNotStored)) + }) + + t.Run("not found", func(t *testing.T) { + must.True(t, benign(ErrNotFound)) + }) + + t.Run("conflict", func(t *testing.T) { + must.True(t, benign(ErrConflict)) + }) + + t.Run("non numeric", func(t *testing.T) { + must.True(t, benign(ErrNonNumeric)) + }) + + t.Run("transport", func(t *testing.T) { + must.False(t, benign(io.EOF)) + must.False(t, benign(errors.New("boom"))) + }) + + t.Run("unexpected", func(t *testing.T) { + must.False(t, benign(unexpected([]byte("SERVER_ERROR\r\n")))) + }) +} + func Test_SetDefaultTTL(t *testing.T) { t.Parallel() diff --git a/verbs.go b/verbs.go index b21050e..74ddd69 100644 --- a/verbs.go +++ b/verbs.go @@ -28,6 +28,27 @@ var ( ErrCommandIssue = errors.New("memc: got command error response") ) +// benign reports whether err represents a normal, expected memcached response +// (or no error at all), meaning the underlying connection is still in a clean, +// reusable state. A non-benign error indicates a transport or protocol failure +// and the connection should be discarded rather than returned to the pool. +func benign(err error) bool { + switch { + case err == nil: + return true + + case errors.Is(err, ErrCacheMiss), + errors.Is(err, ErrNotStored), + errors.Is(err, ErrNotFound), + errors.Is(err, ErrConflict), + errors.Is(err, ErrNonNumeric): + return true + + default: + return false + } +} + // CAS represents a Compare-And-Swap token used for optimistic locking. // It is returned by Gets and must be provided to CompareAndSwap to atomically update a value. type CAS uint64