-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfactory.go
112 lines (95 loc) · 2.27 KB
/
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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
package wredis
import (
"context"
"errors"
"sort"
"time"
)
type Factory struct {
cfg FactoryConfig
decorators decorators
}
func NewFactory(cfg FactoryConfig, ds ...decoratorID) *Factory {
sort.Sort(decorators(ds))
return &Factory{
cfg: cfg,
decorators: ds,
}
}
type FactoryConfig struct {
Name string
CacheConfig LocalCacheConfig
SingleFlight SingleFlightConfigs
}
func NewBuildConfig() FactoryConfig {
return FactoryConfig{
CacheConfig: NewLocalCacheConfig(),
SingleFlight: make(SingleFlightConfigs, 0),
}
}
func (bc FactoryConfig) WithCacheConfig(cacheConfig LocalCacheConfig) FactoryConfig {
bc.CacheConfig = cacheConfig
return bc
}
func (bc FactoryConfig) WithName(name string) FactoryConfig {
bc.Name = name
return bc
}
func (bc FactoryConfig) WithSingleFlight(opts ...Config[SingleFlightClient]) FactoryConfig {
bc.SingleFlight = opts
return bc
}
func (f Factory) decorate(
ctx context.Context,
client UniversalClient,
id decoratorID,
cfg FactoryConfig,
) UniversalClient {
switch id {
case LRUDecorator:
{
cache := NewLRUCache(
cfg.CacheConfig.Size, cfg.CacheConfig.OnEvict, cfg.CacheConfig.TTL,
)
return NewWithCache(ctx, client, NewTTLCache(cache, time.Second), cfg.CacheConfig)
}
case LFUDecorator:
{
cache := NewLFUCache(
cfg.CacheConfig.Size, cfg.CacheConfig.Samples, cfg.CacheConfig.OnEvict, cfg.CacheConfig.TTL,
)
return NewWithCache(ctx, client, NewTTLCache(cache, time.Second), cfg.CacheConfig)
}
case SingleFlightDecorator:
{
return NewSingleFlight(client, cfg.SingleFlight...)
}
case NamedDecorator:
{
return NewNamedClient(client, cfg.Name)
}
}
return client
}
var ErrCacheDecoratorDuplicate = errors.New("cache decorator duplicate")
func (f Factory) Build(
ctx context.Context,
options IOptions,
configurations ...Configuration,
) (client UniversalClient, err error) {
if !f.decorators.UniqCache() {
return nil, ErrCacheDecoratorDuplicate
}
switch opt := (options).(type) {
case Options:
client = New(opt, configurations...)
case ClusterOptions:
client = NewCluster(opt, configurations...)
case RingOptions:
client = NewRing(opt, configurations...)
}
for _, d := range f.decorators {
client = f.decorate(ctx, client, d, f.cfg)
}
return client, nil
}