|
| 1 | +package gonvif |
| 2 | + |
| 3 | +import ( |
| 4 | + "fmt" |
| 5 | + "strings" |
| 6 | + "time" |
| 7 | + |
| 8 | + "github.com/jellydator/ttlcache/v3" |
| 9 | + "golang.org/x/sync/singleflight" |
| 10 | +) |
| 11 | + |
| 12 | +type ClientPool interface { |
| 13 | + GetClient(baseURL, username, password string, verbose bool) (Client, error) |
| 14 | +} |
| 15 | + |
| 16 | +func NewPool(ttl time.Duration) ClientPool { |
| 17 | + cache := ttlcache.New( |
| 18 | + ttlcache.WithTTL[key, Client](ttl), |
| 19 | + ) |
| 20 | + go cache.Start() |
| 21 | + |
| 22 | + return &pool{ |
| 23 | + cache: cache, |
| 24 | + } |
| 25 | +} |
| 26 | + |
| 27 | +type key struct { |
| 28 | + baseURL string |
| 29 | + username string |
| 30 | + password string |
| 31 | + verbose bool |
| 32 | +} |
| 33 | + |
| 34 | +type pool struct { |
| 35 | + cache *ttlcache.Cache[key, Client] |
| 36 | + group singleflight.Group |
| 37 | +} |
| 38 | + |
| 39 | +func (p *pool) GetClient(baseURL, username, password string, verbose bool) (Client, error) { |
| 40 | + k := key{ |
| 41 | + baseURL: baseURL, |
| 42 | + username: username, |
| 43 | + password: password, |
| 44 | + verbose: verbose, |
| 45 | + } |
| 46 | + item := p.cache.Get(k) |
| 47 | + |
| 48 | + if item != nil { |
| 49 | + return item.Value(), nil |
| 50 | + } |
| 51 | + |
| 52 | + return p.newClientSynced(k) |
| 53 | +} |
| 54 | + |
| 55 | +func (p *pool) newClientSynced(k key) (Client, error) { |
| 56 | + v, err, _ := p.group.Do(k.String(), func() (any, error) { |
| 57 | + return p.newClient(k) |
| 58 | + }) |
| 59 | + if err != nil { |
| 60 | + return nil, err |
| 61 | + } |
| 62 | + return v.(Client), nil |
| 63 | +} |
| 64 | + |
| 65 | +func (p *pool) newClient(k key) (Client, error) { |
| 66 | + client, err := New(k.baseURL, k.username, k.password, k.verbose) |
| 67 | + if err != nil { |
| 68 | + p.cache.Set(k, client, ttlcache.DefaultTTL) |
| 69 | + } |
| 70 | + return client, err |
| 71 | +} |
| 72 | + |
| 73 | +var escaper = strings.NewReplacer( |
| 74 | + "\\", "\\\\", |
| 75 | + "|", "\\|", |
| 76 | +) |
| 77 | + |
| 78 | +func (k key) String() string { |
| 79 | + return fmt.Sprintf("%s|%s|%s|%v", |
| 80 | + escaper.Replace(k.baseURL), |
| 81 | + escaper.Replace(k.password), |
| 82 | + escaper.Replace(k.username), |
| 83 | + k.verbose) |
| 84 | +} |
0 commit comments