Merge branch 'master' into 6507-node-manager-azure
[arvados.git] / sdk / go / arvadosclient / pool.go
1 package arvadosclient
2
3 import (
4         "sync"
5 )
6
7 // A ClientPool is a pool of ArvadosClients. This is useful for
8 // applications that make API calls using a dynamic set of tokens,
9 // like web services that pass through their own clients'
10 // credentials. See arvados-git-httpd for an example, and sync.Pool
11 // for more information about garbage collection.
12 type ClientPool struct {
13         sync.Pool
14         lastErr error
15 }
16
17 // MakeClientPool returns a new empty ClientPool.
18 func MakeClientPool() *ClientPool {
19         p := &ClientPool{}
20         p.Pool = sync.Pool{New: func() interface{} {
21                 arv, err := MakeArvadosClient()
22                 if err != nil {
23                         p.lastErr = err
24                         return nil
25                 }
26                 return &arv
27         }}
28         return p
29 }
30
31 // Err returns the error that was encountered last time Get returned
32 // nil.
33 func (p *ClientPool) Err() error {
34         return p.lastErr
35 }
36
37 // Get returns an ArvadosClient taken from the pool, or a new one if
38 // the pool is empty. If an existing client is returned, its state
39 // (including its ApiToken) will be just as it was when it was Put
40 // back in the pool.
41 func (p *ClientPool) Get() *ArvadosClient {
42         c, ok := p.Pool.Get().(*ArvadosClient)
43         if !ok {
44                 return nil
45         }
46         return c
47 }
48
49 // Put puts an ArvadosClient back in the pool.
50 func (p *ClientPool) Put(c *ArvadosClient) {
51         p.Pool.Put(c)
52 }