-
Notifications
You must be signed in to change notification settings - Fork 0
/
kameleoon_client_factory.go
58 lines (50 loc) · 1.5 KB
/
kameleoon_client_factory.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
package kameleoon
import (
cmap "github.com/orcaman/concurrent-map/v2"
)
var KameleoonClientFactory = newKameleoonClientFactory()
type kameleoonClientFactory struct {
clients cmap.ConcurrentMap[string, *kameleoonClient]
}
func newKameleoonClientFactory() *kameleoonClientFactory {
return &kameleoonClientFactory{
clients: cmap.New[*kameleoonClient](),
}
}
func (cf *kameleoonClientFactory) Create(siteCode string, cfg *KameleoonClientConfig) (KameleoonClient, error) {
return cf.createWithConfigSource(siteCode, func() (*KameleoonClientConfig, error) {
return cfg, nil
})
}
func (cf *kameleoonClientFactory) CreateFromFile(siteCode string, cfgPath string) (KameleoonClient, error) {
return cf.createWithConfigSource(siteCode, func() (*KameleoonClientConfig, error) {
return LoadConfig(cfgPath)
})
}
func (cf *kameleoonClientFactory) createWithConfigSource(siteCode string,
cfgSrc func() (*KameleoonClientConfig, error)) (KameleoonClient, error) {
var err error
return cf.clients.Upsert(siteCode, nil,
func(exist bool, former, _ *kameleoonClient) *kameleoonClient {
if former != nil {
return former
}
cfg, cerr := cfgSrc()
if cerr == nil {
client, cerr := newClient(siteCode, cfg)
if cerr == nil {
return client
}
}
err = cerr
return nil
}), err
}
func (cf *kameleoonClientFactory) Forget(siteCode string) {
cf.clients.RemoveCb(siteCode, func(_ string, client *kameleoonClient, exists bool) bool {
if client != nil {
client.close()
}
return true
})
}