Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

conncache - skip caching errors #5418

Open
wants to merge 13 commits into
base: main
Choose a base branch
from
Open
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
1 change: 1 addition & 0 deletions cli/cmd/runtime/start.go
Original file line number Diff line number Diff line change
Expand Up @@ -201,6 +201,7 @@ func StartCmd(ch *cmdutil.Helper) *cobra.Command {
// Init runtime
opts := &runtime.Options{
ConnectionCacheSize: conf.ConnectionCacheSize,
ConnectionCacheErrorTTL: time.Minute,
MetastoreConnector: "metastore",
QueryCacheSizeBytes: conf.QueryCacheSizeBytes,
SecurityEngineCacheSize: conf.SecurityEngineCacheSize,
Expand Down
1 change: 1 addition & 0 deletions cli/pkg/local/app.go
Original file line number Diff line number Diff line change
Expand Up @@ -167,6 +167,7 @@ func NewApp(ctx context.Context, opts *AppOptions) (*App, error) {
SecurityEngineCacheSize: 1000,
ControllerLogBufferCapacity: 10000,
ControllerLogBufferSizeBytes: int64(datasize.MB * 16),
ConnectionCacheErrorTTL: time.Minute,
}
rt, err := runtime.New(ctx, rtOpts, logger, opts.Ch.Telemetry(ctx), email.New(sender))
if err != nil {
Expand Down
1 change: 1 addition & 0 deletions runtime/connection_cache.go
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ func (r *Runtime) newConnectionCache() conncache.Cache {
MaxIdleConnections: r.opts.ConnectionCacheSize,
OpenTimeout: 10 * time.Minute,
CloseTimeout: 10 * time.Minute,
ErrorTTL: r.opts.ConnectionCacheErrorTTL,
CheckHangingInterval: time.Minute,
OpenFunc: func(ctx context.Context, cfg any) (conncache.Connection, error) {
x := cfg.(cachedConnectionConfig)
Expand Down
14 changes: 13 additions & 1 deletion runtime/drivers/druid/druidsqldriver/druid_api_sql_driver.go
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,10 @@ type sqlConnection struct {
dsn string
}

var _ driver.QueryerContext = &sqlConnection{}
var (
_ driver.QueryerContext = &sqlConnection{}
_ driver.Pinger = &sqlConnection{}
)

func (c *sqlConnection) Prepare(query string) (driver.Stmt, error) {
return &stmt{
Expand Down Expand Up @@ -257,6 +260,15 @@ func createTransformer(columnType string) func(any) (any, error) {
}
}

func (c *sqlConnection) Ping(ctx context.Context) error {
rows, err := c.QueryContext(ctx, "SELECT 1", nil)
if err != nil {
return err
}
rows.Close()
return nil
}

type druidRows struct {
closer io.ReadCloser
dec *json.Decoder
Expand Down
109 changes: 70 additions & 39 deletions runtime/pkg/conncache/conncache.go
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,8 @@ type Options struct {
HangingFunc func(cfg any, open bool)
// Metrics are optional instruments for observability.
Metrics Metrics
// The maximum time the error stays in cache
ErrorTTL time.Duration
}

// Metrics are optional instruments for observability. If an instrument is nil, it will not be collected.
Expand Down Expand Up @@ -149,6 +151,8 @@ func (c *cacheImpl) Acquire(ctx context.Context, cfg any) (Connection, ReleaseFu
}

e, ok := c.entries[k]
reopen := ok && e.status == entryStatusOpen && e.err != nil && time.Since(e.since) > c.opts.ErrorTTL

if !ok {
e = &entry{cfg: cfg, since: time.Now()}
c.entries[k] = e
Expand All @@ -159,7 +163,7 @@ func (c *cacheImpl) Acquire(ctx context.Context, cfg any) (Connection, ReleaseFu

c.retainEntry(k, e)

if e.status == entryStatusOpen {
if e.status == entryStatusOpen && !reopen {
defer c.mu.Unlock()
if e.err != nil {
c.releaseEntry(k, e)
Expand Down Expand Up @@ -207,37 +211,37 @@ func (c *cacheImpl) Acquire(ctx context.Context, cfg any) (Connection, ReleaseFu
ch = make(chan struct{})
c.singleflight[k] = ch

e.status = entryStatusOpening
e.since = time.Now()
e.handle = nil
e.err = nil
if !reopen {
e.status = entryStatusOpening
e.since = time.Now()
e.handle = nil
e.err = nil
}

go func() {
start := time.Now()
var handle Connection
var err error
if c.opts.OpenTimeout == 0 {
handle, err = c.opts.OpenFunc(c.ctx, cfg)
} else {
ctx, cancel := context.WithTimeout(c.ctx, c.opts.OpenTimeout)
handle, err = c.opts.OpenFunc(ctx, cfg)
cancel()
}

if c.opts.Metrics.Opens != nil {
c.opts.Metrics.Opens.Add(c.ctx, 1)
var closeErr, err error
handle := e.handle
if reopen {
closeErr = c.closeConnection(e)
}
if c.opts.Metrics.OpenLatencyMS != nil {
c.opts.Metrics.OpenLatencyMS.Record(c.ctx, time.Since(start).Milliseconds())
if closeErr != nil || !reopen {
handle, err = c.openConnection(cfg)
}

c.mu.Lock()
defer c.mu.Unlock()

e.status = entryStatusOpen
e.since = time.Now()
e.handle = handle
e.err = err
if closeErr != nil {
e.status = entryStatusClosed
e.since = time.Now()
e.handle = nil
e.err = closeErr
} else {
e.status = entryStatusOpen
e.since = time.Now()
e.handle = handle
e.err = err
}

delete(c.singleflight, k)
close(ch)
Expand Down Expand Up @@ -278,6 +282,28 @@ func (c *cacheImpl) Acquire(ctx context.Context, cfg any) (Connection, ReleaseFu
return e.handle, c.releaseFunc(k, e), nil
}

func (c *cacheImpl) openConnection(cfg any) (Connection, error) {
start := time.Now()
var handle Connection
var err error
if c.opts.OpenTimeout == 0 {
handle, err = c.opts.OpenFunc(c.ctx, cfg)
} else {
ctx, cancel := context.WithTimeout(c.ctx, c.opts.OpenTimeout)
handle, err = c.opts.OpenFunc(ctx, cfg)
cancel()
}

if c.opts.Metrics.Opens != nil {
c.opts.Metrics.Opens.Add(c.ctx, 1)
}
if c.opts.Metrics.OpenLatencyMS != nil {
c.opts.Metrics.OpenLatencyMS.Record(c.ctx, time.Since(start).Milliseconds())
}

return handle, err
}

func (c *cacheImpl) EvictWhere(predicate func(cfg any) bool) {
c.mu.Lock()
defer c.mu.Unlock()
Expand Down Expand Up @@ -358,21 +384,7 @@ func (c *cacheImpl) beginClose(k string, e *entry) {
e.since = time.Now()

go func() {
start := time.Now()
var err error
if e.handle != nil {
err = e.handle.Close()
}
if err == nil {
err = errors.New("conncache: connection closed")
}

if c.opts.Metrics.Closes != nil {
c.opts.Metrics.Closes.Add(c.ctx, 1)
}
if c.opts.Metrics.CloseLatencyMS != nil {
c.opts.Metrics.CloseLatencyMS.Record(c.ctx, time.Since(start).Milliseconds())
}
err := c.closeConnection(e)

c.mu.Lock()
defer c.mu.Unlock()
Expand All @@ -389,6 +401,25 @@ func (c *cacheImpl) beginClose(k string, e *entry) {
}()
}

func (c *cacheImpl) closeConnection(e *entry) error {
start := time.Now()
var err error
if e.handle != nil {
err = e.handle.Close()
}
if err == nil {
err = errors.New("conncache: connection closed")
}

if c.opts.Metrics.Closes != nil {
c.opts.Metrics.Closes.Add(c.ctx, 1)
}
if c.opts.Metrics.CloseLatencyMS != nil {
c.opts.Metrics.CloseLatencyMS.Record(c.ctx, time.Since(start).Milliseconds())
}
return err
}

func (c *cacheImpl) lruEvictionHandler(key, value any) {
k := key.(string)
e := value.(*entry)
Expand Down
90 changes: 90 additions & 0 deletions runtime/pkg/conncache/conncache_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,96 @@ func (c *mockConn) Close() error {
return nil
}

func TestImpl_count_1(t *testing.T) {
opens := atomic.Int64{}
c := New(Options{
MaxIdleConnections: 2,
OpenFunc: func(ctx context.Context, cfg any) (Connection, error) {
opens.Add(1)
return &mockConn{cfg: cfg.(string)}, nil
},
KeyFunc: func(cfg any) string {
return cfg.(string)
},
})
ci := c.(*cacheImpl)
_, r1, err := c.Acquire(context.Background(), "foo")
require.NoError(t, err)
time.Sleep(time.Second)
require.Equal(t, 1, len(ci.entries))
require.Equal(t, 1, ci.entries["foo"].refs)
require.Equal(t, 0, ci.lru.Len())

_, r2, err := c.Acquire(context.Background(), "foo")
require.Equal(t, 1, len(ci.entries))
require.Equal(t, 0, ci.lru.Len())
r1()
require.Equal(t, 1, len(ci.entries))
require.Equal(t, 0, ci.lru.Len())
r2()
require.Equal(t, 1, len(ci.entries))
require.Equal(t, 1, ci.lru.Len())

require.NoError(t, c.Close(context.Background()))
}

func TestImpl_err(t *testing.T) {
opens := atomic.Int64{}
c := New(Options{
MaxIdleConnections: 1,
OpenFunc: func(ctx context.Context, cfg any) (Connection, error) {
opens.Add(1)
return nil, fmt.Errorf("err")
},
KeyFunc: func(cfg any) string {
return cfg.(string)
},
ErrorTTL: time.Minute,
})
ci := c.(*cacheImpl)
_, _, err := c.Acquire(context.Background(), "foo")
require.Error(t, err)
time.Sleep(time.Second)
require.Equal(t, 1, len(ci.entries))
require.Equal(t, 1, ci.lru.Len())

_, _, err = c.Acquire(context.Background(), "foo")
require.Error(t, err)
require.Equal(t, 1, len(ci.entries))
require.Equal(t, 1, ci.lru.Len())

require.NoError(t, c.Close(context.Background()))
}

func TestImpl_lru(t *testing.T) {
opens := atomic.Int64{}
c := New(Options{
MaxIdleConnections: 1,
OpenFunc: func(ctx context.Context, cfg any) (Connection, error) {
opens.Add(1)
return &mockConn{cfg: cfg.(string)}, nil
},
KeyFunc: func(cfg any) string {
return cfg.(string)
},
})
ci := c.(*cacheImpl)
_, r1, err := c.Acquire(context.Background(), "foo")
require.NoError(t, err)
_, r2, err := c.Acquire(context.Background(), "foo2")
require.Equal(t, 2, len(ci.entries))
require.Equal(t, 0, ci.lru.Len())
r1()
require.Equal(t, 2, len(ci.entries))
require.Equal(t, 1, ci.lru.Len())
r2()
time.Sleep(time.Second)
require.Equal(t, 1, len(ci.entries))
require.Equal(t, 1, ci.lru.Len())

require.NoError(t, c.Close(context.Background()))
}

func TestBasic(t *testing.T) {
opens := atomic.Int64{}

Expand Down
1 change: 1 addition & 0 deletions runtime/runtime.go
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ type Options struct {
ControllerLogBufferSizeBytes int64
AllowHostAccess bool
DataDir string
ConnectionCacheErrorTTL time.Duration
}

type Runtime struct {
Expand Down
2 changes: 2 additions & 0 deletions runtime/testruntime/testruntime.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import (
goruntime "runtime"
"strconv"
"testing"
"time"

"github.com/c2h5oh/datasize"
"github.com/joho/godotenv"
Expand Down Expand Up @@ -60,6 +61,7 @@ func New(t TestingT) *runtime.Runtime {
},
},
ConnectionCacheSize: 100,
ConnectionCacheErrorTTL: time.Minute,
QueryCacheSizeBytes: int64(datasize.MB * 100),
SecurityEngineCacheSize: 100,
ControllerLogBufferCapacity: 10000,
Expand Down
Loading