This repository was archived by the owner on Aug 30, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 18
feat: Add DialCache for key-based connection caching #391
Merged
Changes from 1 commit
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
91c4f66
feat: Add DialCache for key-based connection caching
kylecarbs 857a743
Remove DialOptions
kylecarbs 0af7789
Move DialFunc to Dial
kylecarbs 6aa8048
Add WS options to dial
kylecarbs b0c0167
Requested changes
kylecarbs 1199814
Add comment
kylecarbs 844385e
Fixup
kylecarbs File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,154 @@ | ||
package wsnet | ||
|
||
import ( | ||
"context" | ||
"sync" | ||
"time" | ||
|
||
"golang.org/x/sync/singleflight" | ||
) | ||
|
||
// dialerFunc is used to reference a dialer returned for caching. | ||
type dialerFunc func(ctx context.Context, key string, options *DialOptions) (*Dialer, error) | ||
|
||
// DialCache constructs a new DialerCache. | ||
// The cache clears connections that: | ||
// 1. Are older than the TTL and have no active user-created connections. | ||
// 2. Have been closed. | ||
func DialCache(ttl time.Duration, dialer dialerFunc) *DialerCache { | ||
dc := &DialerCache{ | ||
ttl: ttl, | ||
dialerFunc: dialer, | ||
closed: make(chan struct{}), | ||
flightGroup: &singleflight.Group{}, | ||
mut: sync.RWMutex{}, | ||
dialers: make(map[string]*Dialer), | ||
atime: make(map[string]time.Time), | ||
} | ||
go dc.init() | ||
return dc | ||
} | ||
|
||
type DialerCache struct { | ||
dialerFunc dialerFunc | ||
ttl time.Duration | ||
flightGroup *singleflight.Group | ||
|
||
closed chan struct{} | ||
mut sync.RWMutex | ||
dialers map[string]*Dialer | ||
atime map[string]time.Time | ||
} | ||
|
||
// init starts the ticker for evicting connections. | ||
func (d *DialerCache) init() { | ||
ticker := time.NewTicker(time.Second * 30) | ||
defer ticker.Stop() | ||
for { | ||
select { | ||
case <-d.closed: | ||
return | ||
case <-ticker.C: | ||
d.evict() | ||
} | ||
} | ||
} | ||
|
||
// evict removes lost/broken/expired connections from the cache. | ||
func (d *DialerCache) evict() { | ||
var wg sync.WaitGroup | ||
d.mut.RLock() | ||
for key, dialer := range d.dialers { | ||
wg.Add(1) | ||
key := key | ||
dialer := dialer | ||
go func() { | ||
defer wg.Done() | ||
|
||
evict := false | ||
select { | ||
case <-dialer.Closed(): | ||
evict = true | ||
default: | ||
} | ||
deansheather marked this conversation as resolved.
Show resolved
Hide resolved
|
||
if dialer.ActiveConnections() == 0 && time.Since(d.atime[key]) >= d.ttl { | ||
evict = true | ||
} | ||
if !evict { | ||
ctx, cancel := context.WithTimeout(context.Background(), time.Second*15) | ||
defer cancel() | ||
err := dialer.Ping(ctx) | ||
if err != nil { | ||
evict = true | ||
} | ||
} | ||
|
||
if evict { | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. else There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Huh? There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Use There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Ahh the other one is to ping only if can't evict. |
||
_ = dialer.Close() | ||
d.mut.Lock() | ||
delete(d.atime, key) | ||
delete(d.dialers, key) | ||
kylecarbs marked this conversation as resolved.
Show resolved
Hide resolved
|
||
d.mut.Unlock() | ||
kylecarbs marked this conversation as resolved.
Show resolved
Hide resolved
|
||
} | ||
}() | ||
} | ||
d.mut.RUnlock() | ||
wg.Wait() | ||
} | ||
|
||
// Dial returns a Dialer from the cache if one exists with the key provided, | ||
// or dials a new connection using the dialerFunc. | ||
kylecarbs marked this conversation as resolved.
Show resolved
Hide resolved
|
||
func (d *DialerCache) Dial(ctx context.Context, key string, options *DialOptions) (*Dialer, bool, error) { | ||
d.mut.RLock() | ||
if dialer, ok := d.dialers[key]; ok { | ||
kylecarbs marked this conversation as resolved.
Show resolved
Hide resolved
|
||
closed := false | ||
select { | ||
case <-dialer.Closed(): | ||
closed = true | ||
default: | ||
} | ||
if !closed { | ||
d.mut.RUnlock() | ||
d.mut.Lock() | ||
d.atime[key] = time.Now() | ||
d.mut.Unlock() | ||
|
||
return dialer, true, nil | ||
} | ||
} | ||
d.mut.RUnlock() | ||
|
||
dialer, err, _ := d.flightGroup.Do(key, func() (interface{}, error) { | ||
dialer, err := d.dialerFunc(ctx, key, options) | ||
if err != nil { | ||
return nil, err | ||
} | ||
d.mut.Lock() | ||
d.dialers[key] = dialer | ||
d.atime[key] = time.Now() | ||
d.mut.Unlock() | ||
|
||
return dialer, nil | ||
}) | ||
if err != nil { | ||
return nil, false, err | ||
} | ||
return dialer.(*Dialer), false, nil | ||
} | ||
|
||
// Close closes all cached dialers. | ||
func (d *DialerCache) Close() error { | ||
d.mut.Lock() | ||
defer d.mut.Unlock() | ||
|
||
for key, dialer := range d.dialers { | ||
d.flightGroup.Forget(key) | ||
|
||
kylecarbs marked this conversation as resolved.
Show resolved
Hide resolved
|
||
err := dialer.Close() | ||
if err != nil { | ||
return err | ||
} | ||
} | ||
close(d.closed) | ||
kylecarbs marked this conversation as resolved.
Show resolved
Hide resolved
|
||
return nil | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,67 @@ | ||
package wsnet | ||
|
||
import ( | ||
"context" | ||
"testing" | ||
"time" | ||
|
||
"cdr.dev/slog/sloggers/slogtest" | ||
"github.com/stretchr/testify/require" | ||
) | ||
|
||
func TestCache(t *testing.T) { | ||
t.Run("Caches", func(t *testing.T) { | ||
connectAddr, listenAddr := createDumbBroker(t) | ||
l, err := Listen(context.Background(), slogtest.Make(t, nil), listenAddr, "") | ||
require.NoError(t, err) | ||
defer l.Close() | ||
|
||
cache := DialCache(time.Hour, func(ctx context.Context, key string, options *DialOptions) (*Dialer, error) { | ||
return DialWebsocket(ctx, connectAddr, options) | ||
}) | ||
_, cached, err := cache.Dial(context.Background(), "example", nil) | ||
require.NoError(t, err) | ||
require.Equal(t, cached, false) | ||
_, cached, err = cache.Dial(context.Background(), "example", nil) | ||
require.NoError(t, err) | ||
require.Equal(t, cached, true) | ||
}) | ||
|
||
t.Run("Create If Closed", func(t *testing.T) { | ||
connectAddr, listenAddr := createDumbBroker(t) | ||
l, err := Listen(context.Background(), slogtest.Make(t, nil), listenAddr, "") | ||
require.NoError(t, err) | ||
defer l.Close() | ||
|
||
cache := DialCache(time.Hour, func(ctx context.Context, key string, options *DialOptions) (*Dialer, error) { | ||
return DialWebsocket(ctx, connectAddr, options) | ||
}) | ||
|
||
conn, cached, err := cache.Dial(context.Background(), "example", nil) | ||
require.NoError(t, err) | ||
require.Equal(t, cached, false) | ||
require.NoError(t, conn.Close()) | ||
_, cached, err = cache.Dial(context.Background(), "example", nil) | ||
require.NoError(t, err) | ||
require.Equal(t, cached, false) | ||
}) | ||
|
||
t.Run("Evict No Connections", func(t *testing.T) { | ||
connectAddr, listenAddr := createDumbBroker(t) | ||
l, err := Listen(context.Background(), slogtest.Make(t, nil), listenAddr, "") | ||
require.NoError(t, err) | ||
defer l.Close() | ||
|
||
cache := DialCache(0, func(ctx context.Context, key string, options *DialOptions) (*Dialer, error) { | ||
return DialWebsocket(ctx, connectAddr, options) | ||
}) | ||
|
||
_, cached, err := cache.Dial(context.Background(), "example", nil) | ||
require.NoError(t, err) | ||
require.Equal(t, cached, false) | ||
cache.evict() | ||
_, cached, err = cache.Dial(context.Background(), "example", nil) | ||
require.NoError(t, err) | ||
require.Equal(t, cached, false) | ||
kylecarbs marked this conversation as resolved.
Show resolved
Hide resolved
|
||
}) | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.