[#549] clientCache: Add TLS to client

Signed-off-by: Pavel Karpy <carpawell@nspcc.ru>
This commit is contained in:
Pavel Karpy 2021-05-18 09:26:45 +03:00 committed by Alex Vanin
parent f267fbc56a
commit f89c8bf239

View file

@ -1,6 +1,7 @@
package cache package cache
import ( import (
"crypto/tls"
"fmt" "fmt"
"sync" "sync"
@ -30,13 +31,13 @@ func NewSDKClientCache(opts ...client.Option) *ClientCache {
// Get function returns existing client or creates a new one. // Get function returns existing client or creates a new one.
func (c *ClientCache) Get(netAddr *network.Address) (client.Client, error) { func (c *ClientCache) Get(netAddr *network.Address) (client.Client, error) {
hostAddr, err := netAddr.HostAddrString() // multiaddr is used as a key in client cache since
if err != nil { // same host may have different connections(with tls or not),
return nil, fmt.Errorf("could not parse address as a string: %w", err) // therefore, host+port pair is not unique
} mAddr := netAddr.String()
c.mu.RLock() c.mu.RLock()
if cli, ok := c.clients[hostAddr]; ok { if cli, ok := c.clients[mAddr]; ok {
// todo: check underlying connection neofs-api-go#196 // todo: check underlying connection neofs-api-go#196
c.mu.RUnlock() c.mu.RUnlock()
@ -50,18 +51,27 @@ func (c *ClientCache) Get(netAddr *network.Address) (client.Client, error) {
// check once again if client is missing in cache, concurrent routine could // check once again if client is missing in cache, concurrent routine could
// create client while this routine was locked on `c.mu.Lock()`. // create client while this routine was locked on `c.mu.Lock()`.
if cli, ok := c.clients[hostAddr]; ok { if cli, ok := c.clients[mAddr]; ok {
return cli, nil return cli, nil
} }
hostAddr, err := netAddr.HostAddrString()
if err != nil {
return nil, fmt.Errorf("could not parse address as a string: %w", err)
}
opts := append(c.opts, client.WithAddress(hostAddr)) opts := append(c.opts, client.WithAddress(hostAddr))
if netAddr.TLSEnabled() {
opts = append(opts, client.WithTLSConfig(&tls.Config{}))
}
cli, err := client.New(opts...) cli, err := client.New(opts...)
if err != nil { if err != nil {
return nil, err return nil, err
} }
c.clients[hostAddr] = cli c.clients[mAddr] = cli
return cli, nil return cli, nil
} }