From 6daccc75fc85c8e96c9be858170437c3f4c53cde Mon Sep 17 00:00:00 2001 From: Seth Hoenig Date: Sun, 29 Nov 2026 17:53:20 -0600 Subject: [PATCH] iopool: set io timeouts --- Justfile | 2 +- README.md | 23 +++++++++++++++++++++++ client.go | 33 +++++++++++++++++++++++++++++++-- client_test.go | 40 ++++++++++++++++++++++++++++++++++++++-- go.mod | 1 + go.sum | 2 ++ iopool/mock.go | 11 +++++++++-- iopool/pool.go | 37 ++++++++++++++++++++++++++----------- iopool/pool_test.go | 43 +++++++++++++++++++++++++++++++++++-------- 9 files changed, 166 insertions(+), 26 deletions(-) diff --git a/Justfile b/Justfile index 8e310bc..50fe5e4 100644 --- a/Justfile +++ b/Justfile @@ -42,4 +42,4 @@ lint: vet # locally install build dependencies [group('build')] init: - go install github.com/golangci/golangci-lint/v2/cmd/golangci-lint@v2.13.0 + go install github.com/golangci/golangci-lint/v2/cmd/golangci-lint@v2.15.0 diff --git a/README.md b/README.md index c214f1c..908b45c 100644 --- a/README.md +++ b/README.md @@ -129,6 +129,29 @@ client := memc.New( ) ``` +##### Configuring timeouts. + +The dial timeout controls how long to wait while establishing a connection to a +memcached instance. A non-positive value falls back to the default of 5 seconds. + +```go +client := memc.New( + // ... + SetDialTimeout(2 * time.Second), +) +``` + +The I/O timeout bounds each request's read/write operations on an established +connection. It is disabled by default (0), meaning a stalled connection may +block indefinitely unless configured. + +```go +client := memc.New( + // ... + SetIOTimeout(10 * time.Second), +) +``` + ##### Closing the client. The `Client` can be closed so that idle connections are closed and no longer diff --git a/client.go b/client.go index 43ec1f0..07016e6 100644 --- a/client.go +++ b/client.go @@ -9,6 +9,7 @@ import ( "time" "cattlecloud.net/go/memc/iopool" + "github.com/shoenig/lang" ) // A Client is used for making network requests to memcached instances. @@ -17,6 +18,7 @@ import ( // manage data in memcached. type Client struct { timeout time.Duration + iotimeout time.Duration expiration time.Duration idle int now func() time.Time @@ -61,11 +63,27 @@ func SetIdleConnections(count int) ClientOption { // connection to the memached instance(s). // // If unset the default timeout is 5 seconds. +// +// A non-positive timeout is ignored, falling back to the default. func SetDialTimeout(timeout time.Duration) ClientOption { return func(c *Client) { c.lock.Lock() defer c.lock.Unlock() - c.timeout = timeout + c.timeout = lang.Maybe(timeout > 0, timeout, defaultDialTimeout) + } +} + +// SetIOTimeout adjusts the amount of time to wait on read/write operations +// against an established connection. +// +// If unset, no deadline is applied (0), meaning operations may block +// indefinitely on a stalled connection. Set a positive duration to bound each +// request's I/O. A non-positive timeout disables the deadline. +func SetIOTimeout(timeout time.Duration) ClientOption { + return func(c *Client) { + c.lock.Lock() + defer c.lock.Unlock() + c.iotimeout = lang.Maybe(timeout >= 0, timeout, 0) } } @@ -106,6 +124,7 @@ const ( defaultDialTimeout = 5 * time.Second defaultExpiration = 1 * time.Hour defaultIdleCount = 1 + defaultIOTimeout = 0 ) // New creates a new Client capable of sharding across the given set of @@ -117,6 +136,7 @@ func New(instances []string, opts ...ClientOption) *Client { c := new(Client) c.addrs = instances c.timeout = defaultDialTimeout + c.iotimeout = defaultIOTimeout c.expiration = defaultExpiration c.idle = defaultIdleCount c.now = time.Now @@ -125,7 +145,7 @@ func New(instances []string, opts ...ClientOption) *Client { opt(c) } - c.pools = iopool.New(c.addrs, c.idle) + c.pools = iopool.New(c.addrs, c.idle, c.timeout) return c } @@ -174,6 +194,15 @@ func (c *Client) do(key string, f func(*iopool.Buffer) error) error { if err != nil { return err } + + if c.iotimeout > 0 { + if derr := conn.SetDeadline(c.now().Add(c.iotimeout)); derr != nil { + conn.SetHealth(derr) + c.setConn(key, conn) + return derr + } + } + err = f(conn) conn.SetHealth(err) c.setConn(key, conn) diff --git a/client_test.go b/client_test.go index a2111df..a9e9fe7 100644 --- a/client_test.go +++ b/client_test.go @@ -15,8 +15,44 @@ import ( func Test_SetDialTimeout(t *testing.T) { t.Parallel() - c := New(nil, SetDialTimeout(4*time.Second)) - must.Eq(t, 4*time.Second, c.timeout) + t.Run("positive", func(t *testing.T) { + c := New(nil, SetDialTimeout(4*time.Second)) + must.Eq(t, 4*time.Second, c.timeout) + }) + + t.Run("zero", func(t *testing.T) { + c := New(nil, SetDialTimeout(0)) + must.Eq(t, defaultDialTimeout, c.timeout) + }) + + t.Run("negative", func(t *testing.T) { + c := New(nil, SetDialTimeout(-time.Second)) + must.Eq(t, defaultDialTimeout, c.timeout) + }) +} + +func Test_SetIOTimeout(t *testing.T) { + t.Parallel() + + t.Run("default", func(t *testing.T) { + c := New(nil) + must.Zero(t, c.iotimeout) + }) + + t.Run("positive", func(t *testing.T) { + c := New(nil, SetIOTimeout(10*time.Second)) + must.Eq(t, 10*time.Second, c.iotimeout) + }) + + t.Run("zero", func(t *testing.T) { + c := New(nil, SetIOTimeout(0)) + must.Zero(t, c.iotimeout) + }) + + t.Run("negative", func(t *testing.T) { + c := New(nil, SetIOTimeout(-time.Second)) + must.Zero(t, c.iotimeout) + }) } func Test_SetDefaultTTL(t *testing.T) { diff --git a/go.mod b/go.mod index 21c52ef..b084c10 100644 --- a/go.mod +++ b/go.mod @@ -6,6 +6,7 @@ require ( cattlecloud.net/go/scope v1.3.0 cattlecloud.net/go/stacks v1.1.3 github.com/shoenig/ignore v0.4.0 + github.com/shoenig/lang v0.0.9 github.com/shoenig/test v1.13.2 ) diff --git a/go.sum b/go.sum index aaf96ed..0b5e410 100644 --- a/go.sum +++ b/go.sum @@ -6,5 +6,7 @@ github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8= github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU= github.com/shoenig/ignore v0.4.0 h1:qPOWs0slbPMtenC0H3cKvu5Kn3hQFTE3yK6YJvyNDlA= github.com/shoenig/ignore v0.4.0/go.mod h1:VF91FoiYAwXq4KinOq6zP5xfFw/Ib6MfftaGKYTpmwo= +github.com/shoenig/lang v0.0.9 h1:pbEDv1T2NT1CK5WbcegG5UZMoJwR+/nvsLCxTYeOTKs= +github.com/shoenig/lang v0.0.9/go.mod h1:u515SaQYHQgukwYa8K6wftsmSh5aWGxJvSi4zjazNfI= github.com/shoenig/test v1.13.2 h1:SaGxHxg7xkRuKuNtuFmHf0LgNGaAgcBT7HN4WHCKfqU= github.com/shoenig/test v1.13.2/go.mod h1:MKmiRyEeuFl8y9PCoThaRDgYQZeWBhRQlH99poXz5LI= diff --git a/iopool/mock.go b/iopool/mock.go index 6104fca..ebf0dbc 100644 --- a/iopool/mock.go +++ b/iopool/mock.go @@ -5,6 +5,7 @@ package iopool import ( "sync" + "time" ) type mockConn struct { @@ -15,6 +16,7 @@ type mockConn struct { errOnRead error errOnWrite error errOnClose error + deadline time.Time } func (mc *mockConn) Read([]byte) (int, error) { @@ -31,6 +33,11 @@ func (mc *mockConn) Close() error { return mc.errOnClose } +func (mc *mockConn) SetDeadline(t time.Time) error { + mc.deadline = t + return nil +} + func newMockConn(reads, writes []string) *mockConn { return &mockConn{ setReads: reads, @@ -38,9 +45,9 @@ func newMockConn(reads, writes []string) *mockConn { } } -func mockConnections(connections ...*mockConn) func(string) (Connection, error) { +func mockConnections(connections ...*mockConn) func(string, time.Duration) (Connection, error) { i := 0 - return func(string) (Connection, error) { + return func(string, time.Duration) (Connection, error) { next := connections[i] i++ next.sequence = i diff --git a/iopool/pool.go b/iopool/pool.go index 4465dc3..ae8672f 100644 --- a/iopool/pool.go +++ b/iopool/pool.go @@ -6,7 +6,6 @@ package iopool import ( "bufio" "errors" - "io" "net" "strings" "sync/atomic" @@ -33,12 +32,16 @@ type Connection interface { // Close closes the connection. Close() error + + // SetDeadline sets the read and write deadlines associated with the + // connection. + SetDeadline(t time.Time) error } type Buffer struct { *bufio.Reader *bufio.Writer - io.Closer + conn Connection failure *atomic.Bool } @@ -46,21 +49,31 @@ func newBuffer(conn Connection) *Buffer { return &Buffer{ Reader: bufio.NewReader(conn), Writer: bufio.NewWriter(conn), - Closer: conn, + conn: conn, failure: new(atomic.Bool), } } +// Close closes the underlying connection. +func (b *Buffer) Close() error { + return b.conn.Close() +} + +// SetDeadline sets the read and write deadlines on the underlying connection. +func (b *Buffer) SetDeadline(t time.Time) error { + return b.conn.SetDeadline(t) +} + func (b *Buffer) SetHealth(err error) { if err != nil { b.failure.Store(true) } } -func New(instances []string, idle int) *Collection { +func New(instances []string, idle int, timeout time.Duration) *Collection { pools := make([]*pool, 0, len(instances)) for _, instance := range instances { - pools = append(pools, newPool(instance, idle)) + pools = append(pools, newPool(instance, idle, timeout)) } return &Collection{pools: pools} } @@ -110,13 +123,15 @@ type pool struct { address string available stacks.Stack[*Buffer] idle int - openf func(string) (Connection, error) + timeout time.Duration + openf func(string, time.Duration) (Connection, error) } -func newPool(address string, idle int) *pool { +func newPool(address string, idle int, timeout time.Duration) *pool { return &pool{ address: address, idle: idle, + timeout: timeout, openf: open, available: stacks.Simple[*Buffer](), } @@ -138,7 +153,7 @@ func (p *pool) get() (*Buffer, error) { } if p.available.Empty() { - conn, err := p.openf(p.address) + conn, err := p.openf(p.address, p.timeout) if err != nil { return nil, err } @@ -149,10 +164,10 @@ func (p *pool) get() (*Buffer, error) { return b, nil } -func open(address string) (Connection, error) { - dialer := &net.Dialer{Timeout: 3 * time.Second} +func open(address string, timeout time.Duration) (Connection, error) { + dialer := &net.Dialer{Timeout: timeout} - ctx, cancel := scope.TTL(3 * time.Second) + ctx, cancel := scope.TTL(timeout) defer cancel() switch strings.HasPrefix(address, "/") { diff --git a/iopool/pool_test.go b/iopool/pool_test.go index 060cbbf..ca981f3 100644 --- a/iopool/pool_test.go +++ b/iopool/pool_test.go @@ -7,6 +7,7 @@ import ( "errors" "fmt" "testing" + "time" "github.com/shoenig/test/must" ) @@ -32,11 +33,22 @@ func TestBuffer_SetHealth(t *testing.T) { }) } +func TestBuffer_SetDeadline(t *testing.T) { + t.Parallel() + + mc := newMockConn(nil, nil) + b := newBuffer(mc) + + when := time.Date(2026, 1, 2, 3, 4, 5, 0, time.UTC) + must.NoError(t, b.SetDeadline(when)) + must.Eq(t, when, mc.deadline) +} + func TestPool_get(t *testing.T) { t.Parallel() t.Run("closed", func(t *testing.T) { - p := newPool("10.0.0.1", 1) + p := newPool("10.0.0.1", 1, time.Second) p.openf = mockConnections( newMockConn(nil, nil), ) @@ -47,7 +59,7 @@ func TestPool_get(t *testing.T) { }) t.Run("normal", func(t *testing.T) { - p := newPool("10.0.0.1", 1) + p := newPool("10.0.0.1", 1, time.Second) p.openf = mockConnections( newMockConn(nil, nil), ) @@ -57,7 +69,7 @@ func TestPool_get(t *testing.T) { }) t.Run("second", func(t *testing.T) { - p := newPool("10.0.0.1", 1) + p := newPool("10.0.0.1", 1, time.Second) p.openf = mockConnections( newMockConn(nil, nil), newMockConn(nil, nil), @@ -71,13 +83,28 @@ func TestPool_get(t *testing.T) { must.NoError(t, err) must.NotNil(t, c) }) + + t.Run("timeout", func(t *testing.T) { + p := newPool("10.0.0.1", 1, 7*time.Second) + + var captured time.Duration + p.openf = func(_ string, timeout time.Duration) (Connection, error) { + captured = timeout + return newMockConn(nil, nil), nil + } + + c, err := p.get() + must.NoError(t, err) + must.NotNil(t, c) + must.Eq(t, 7*time.Second, captured) + }) } func TestPool_free(t *testing.T) { t.Parallel() t.Run("closed", func(t *testing.T) { - p := newPool("10.0.0.1", 1) + p := newPool("10.0.0.1", 1, time.Second) p.openf = mockConnections( newMockConn(nil, nil), ) @@ -91,7 +118,7 @@ func TestPool_free(t *testing.T) { }) t.Run("full", func(t *testing.T) { - p := newPool("10.0.0.1", 2) + p := newPool("10.0.0.1", 2, time.Second) p.openf = mockConnections( newMockConn(nil, nil), newMockConn(nil, nil), @@ -124,7 +151,7 @@ func TestPool_free(t *testing.T) { }) t.Run("failure", func(t *testing.T) { - p := newPool("10.0.0.1", 2) + p := newPool("10.0.0.1", 2, time.Second) p.openf = mockConnections( newMockConn(nil, nil), ) @@ -166,7 +193,7 @@ func TestCollection_pick_distribution(t *testing.T) { func TestCollection_GetReturn(t *testing.T) { t.Parallel() - p := newPool("10.0.0.1", 1) + p := newPool("10.0.0.1", 1, time.Second) p.openf = mockConnections( newMockConn(nil, nil), ) @@ -184,7 +211,7 @@ func TestCollection_GetReturn(t *testing.T) { func TestCollection_GetCloseReturn(t *testing.T) { t.Parallel() - p := newPool("10.0.0.1", 1) + p := newPool("10.0.0.1", 1, time.Second) p.openf = mockConnections( newMockConn(nil, nil), )