Skip to content

Commit c6328aa

Browse files
committed
fix: guard Substarte connection state in GetClient() and Close()
1 parent b8d84f3 commit c6328aa

File tree

1 file changed

+22
-2
lines changed

1 file changed

+22
-2
lines changed

clients/tfchain-client-go/impl.go

Lines changed: 22 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,8 @@ var (
2727
ErrUnknownVersion = fmt.Errorf("unknown version")
2828
//ErrNotFound is returned if an object is not found
2929
ErrNotFound = fmt.Errorf("object not found")
30+
//ErrClosed is returned if the client is closed
31+
ErrClosed = fmt.Errorf("client closed")
3032
)
3133

3234
// Versioned base for all types
@@ -145,6 +147,9 @@ func (p *mgrImpl) Raw() (Conn, Meta, error) {
145147
return cl, meta, err
146148
}
147149

150+
// connect connects to the next endpoint in roundrobin fashion
151+
// and replaces the current connection with the new one.
152+
// need to be called while lock is acquired.
148153
func (p *mgrImpl) connect(s *Substrate) error {
149154
cl, meta, err := p.Raw()
150155
if err != nil {
@@ -176,8 +181,10 @@ func (p *mgrImpl) put(s *Substrate) {
176181

177182
// Substrate client
178183
type Substrate struct {
179-
cl Conn
180-
meta Meta
184+
mu sync.Mutex
185+
cl Conn
186+
meta Meta
187+
closed bool
181188

182189
close func(s *Substrate)
183190
connect func(s *Substrate) error
@@ -189,10 +196,23 @@ func newSubstrate(cl Conn, meta Meta, close func(*Substrate), connect func(s *Su
189196
}
190197

191198
func (s *Substrate) Close() {
199+
s.mu.Lock()
200+
defer s.mu.Unlock()
201+
if s.closed {
202+
return
203+
}
192204
s.close(s)
205+
s.closed = true
193206
}
194207

195208
func (s *Substrate) GetClient() (Conn, Meta, error) {
209+
s.mu.Lock()
210+
defer s.mu.Unlock()
211+
212+
if s.closed {
213+
return nil, nil, ErrClosed
214+
}
215+
196216
// check if connection is healthy
197217
if _, err := getTime(s.cl, s.meta); err != nil {
198218
log.Info().Str("url", s.cl.Client.URL()).Msg("connection unhealthy, attempting failover")

0 commit comments

Comments
 (0)