2020-11-18 13:01:59 +00:00
|
|
|
package cache
|
|
|
|
|
|
|
|
import (
|
|
|
|
"sync"
|
|
|
|
|
|
|
|
"github.com/nspcc-dev/neofs-api-go/pkg/client"
|
|
|
|
)
|
|
|
|
|
|
|
|
type (
|
|
|
|
// ClientCache is a structure around neofs-api-go/pkg/client to reuse
|
|
|
|
// already created clients.
|
|
|
|
ClientCache struct {
|
|
|
|
mu *sync.RWMutex
|
|
|
|
clients map[string]*client.Client
|
|
|
|
}
|
|
|
|
)
|
|
|
|
|
|
|
|
// NewSDKClientCache creates instance of client cache.
|
|
|
|
func NewSDKClientCache() *ClientCache {
|
|
|
|
return &ClientCache{
|
|
|
|
mu: new(sync.RWMutex),
|
|
|
|
clients: make(map[string]*client.Client),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-11-23 12:58:39 +00:00
|
|
|
// Get function returns existing client or creates a new one.
|
2021-03-13 15:22:21 +00:00
|
|
|
func (c *ClientCache) Get(address string, opts ...client.Option) (*client.Client, error) {
|
2020-11-18 13:01:59 +00:00
|
|
|
c.mu.RLock()
|
2021-03-13 15:22:21 +00:00
|
|
|
if cli, ok := c.clients[address]; ok {
|
2020-11-18 13:01:59 +00:00
|
|
|
// todo: check underlying connection neofs-api-go#196
|
|
|
|
c.mu.RUnlock()
|
|
|
|
|
|
|
|
return cli, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
c.mu.RUnlock()
|
|
|
|
// if client is not found in cache, then create a new one
|
|
|
|
c.mu.Lock()
|
|
|
|
defer c.mu.Unlock()
|
|
|
|
|
|
|
|
// check once again if client is missing in cache, concurrent routine could
|
|
|
|
// create client while this routine was locked on `c.mu.Lock()`.
|
2021-03-13 15:22:21 +00:00
|
|
|
if cli, ok := c.clients[address]; ok {
|
2020-11-18 13:01:59 +00:00
|
|
|
return cli, nil
|
|
|
|
}
|
|
|
|
|
2021-03-13 15:22:21 +00:00
|
|
|
cli, err := client.New(nil, append(opts, client.WithAddress(address))...)
|
2020-11-18 13:01:59 +00:00
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
2021-03-13 15:22:21 +00:00
|
|
|
c.clients[address] = cli
|
2020-11-18 13:01:59 +00:00
|
|
|
|
|
|
|
return cli, nil
|
|
|
|
}
|