Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion Justfile
Original file line number Diff line number Diff line change
Expand Up @@ -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
23 changes: 23 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
33 changes: 31 additions & 2 deletions client.go
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand All @@ -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
Expand Down Expand Up @@ -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)
}
}

Expand Down Expand Up @@ -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
Expand All @@ -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
Expand All @@ -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
}

Expand Down Expand Up @@ -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)
Expand Down
40 changes: 38 additions & 2 deletions client_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down
1 change: 1 addition & 0 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -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
)

Expand Down
2 changes: 2 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -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=
11 changes: 9 additions & 2 deletions iopool/mock.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ package iopool

import (
"sync"
"time"
)

type mockConn struct {
Expand All @@ -15,6 +16,7 @@ type mockConn struct {
errOnRead error
errOnWrite error
errOnClose error
deadline time.Time
}

func (mc *mockConn) Read([]byte) (int, error) {
Expand All @@ -31,16 +33,21 @@ 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,
expWrites: writes,
}
}

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
Expand Down
37 changes: 26 additions & 11 deletions iopool/pool.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ package iopool
import (
"bufio"
"errors"
"io"
"net"
"strings"
"sync/atomic"
Expand All @@ -33,34 +32,48 @@ 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
}

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}
}
Expand Down Expand Up @@ -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](),
}
Expand All @@ -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
}
Expand All @@ -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, "/") {
Expand Down
Loading
Loading