-
Notifications
You must be signed in to change notification settings - Fork 0
/
ember.go
221 lines (188 loc) · 6.26 KB
/
ember.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
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
// Package ember provides a flexible, multi-layer caching solution.
package ember
import (
"context"
"fmt"
"time"
"go.uber.org/zap"
"goflare.io/ember/internal/cache/limited"
"goflare.io/ember/internal/cache/multi"
"goflare.io/ember/internal/config"
"goflare.io/ember/pkg/serialization"
"github.com/redis/go-redis/v9"
)
// CacheOperations defines the interface for cache operations.
type CacheOperations interface {
Set(ctx context.Context, key string, value any, ttl ...time.Duration) error
Get(ctx context.Context, key string, value any) (bool, error)
Delete(ctx context.Context, key string) error
Clear(ctx context.Context) error
GetMulti(ctx context.Context, keys []string) (map[string]any, error)
SetMulti(ctx context.Context, items map[string]any, ttl ...time.Duration) error
Close() error
}
// Option defines a function type for configuring Ember.
type Option func(*config.Config) error
// Ember represents the main structure of the Ember library.
type Ember struct {
cache CacheOperations
logger *zap.Logger
config *config.Config
}
// New initializes the Ember library with the provided options.
func New(ctx context.Context, opts ...Option) (*Ember, error) {
cfg, err := config.NewConfig()
if err != nil {
return nil, fmt.Errorf("failed to create config: %w", err)
}
for _, opt := range opts {
if err := opt(cfg); err != nil {
return nil, fmt.Errorf("failed to apply option: %w", err)
}
}
if cfg.Logger == nil {
logger, err := zap.NewProduction()
if err != nil {
return nil, fmt.Errorf("failed to initialize default logger: %w", err)
}
cfg.Logger = logger
}
var cache CacheOperations
if cfg.RedisOptions != nil {
redisClient := redis.NewClient(cfg.RedisOptions)
if err := redisClient.Ping(ctx).Err(); err != nil {
return nil, fmt.Errorf("failed to connect to Redis: %w", err)
}
cache, err = multi.NewCache(ctx, cfg, redisClient)
} else {
cache, err = limited.New(cfg.MaxLocalSize, cfg.DefaultExpiration, cfg.Logger)
}
if err != nil {
return nil, fmt.Errorf("failed to initialize cache: %w", err)
}
return &Ember{
cache: cache,
logger: cfg.Logger,
config: cfg,
}, nil
}
// Set sets a cache item.
func (e *Ember) Set(ctx context.Context, key string, value any, ttl ...time.Duration) error {
return e.cache.Set(ctx, key, value, ttl...)
}
// Get retrieves a cache item.
func (e *Ember) Get(ctx context.Context, key string, value any) (bool, error) {
return e.cache.Get(ctx, key, value)
}
// Delete removes a cache item.
func (e *Ember) Delete(ctx context.Context, key string) error {
return e.cache.Delete(ctx, key)
}
// Clear removes all cache items.
func (e *Ember) Clear(ctx context.Context) error {
return e.cache.Clear(ctx)
}
// GetMulti retrieves multiple cache items.
func (e *Ember) GetMulti(ctx context.Context, keys []string) (map[string]any, error) {
return e.cache.GetMulti(ctx, keys)
}
// SetMulti sets multiple cache items.
func (e *Ember) SetMulti(ctx context.Context, items map[string]any, ttl ...time.Duration) error {
return e.cache.SetMulti(ctx, items, ttl...)
}
// GetStats returns cache usage statistics if available.
func (e *Ember) GetStats() map[string]any {
if stats, ok := e.cache.(interface{ Stats() map[string]any }); ok {
return stats.Stats()
}
return nil
}
// Close closes the Ember library and releases resources.
func (e *Ember) Close() error {
return e.cache.Close()
}
// Configuration options
// WithLogger sets a custom logger.
func WithLogger(logger *zap.Logger) Option {
return func(cfg *config.Config) error {
cfg.Logger = logger
return nil
}
}
// WithMaxLocalSize sets the maximum size for the local cache.
func WithMaxLocalSize(maxSize uint64) Option {
return func(cfg *config.Config) error {
cfg.MaxLocalSize = maxSize
return nil
}
}
// WithShardCount sets the number of shards for the local cache.
func WithShardCount(shardCount uint64) Option {
return func(cfg *config.Config) error {
cfg.ShardCount = shardCount
return nil
}
}
// WithDefaultExpiration sets the default expiration time for cache items.
func WithDefaultExpiration(ttl time.Duration) Option {
return func(cfg *config.Config) error {
cfg.DefaultExpiration = ttl
return nil
}
}
// WithRedis sets Redis options for distributed caching.
func WithRedis(options *redis.Options) Option {
return func(cfg *config.Config) error {
cfg.RedisOptions = options
return nil
}
}
// WithSerializer sets custom serialization functions.
func WithSerializer(encodeType string) Option {
return func(cfg *config.Config) error {
if encodeType == serialization.GobType {
cfg.Serialization.Encoder = serialization.GobEncoder
cfg.Serialization.Decoder = serialization.GobDecoder
} else {
cfg.Serialization.Encoder = serialization.JSONEncoder
cfg.Serialization.Decoder = serialization.JSONDecoder
}
return nil
}
}
// WithBloomFilter configures the Bloom filter settings.
func WithBloomFilter(expectedItems uint, falsePositiveRate float64) Option {
return func(cfg *config.Config) error {
cfg.CacheBehaviorConfig.BloomFilterSettings.ExpectedItems = expectedItems
cfg.CacheBehaviorConfig.BloomFilterSettings.FalsePositiveRate = falsePositiveRate
return nil
}
}
// WithPrefetch configures the prefetch behavior.
func WithPrefetch(enable bool, threshold, count uint64) Option {
return func(cfg *config.Config) error {
cfg.CacheBehaviorConfig.EnablePrefetch = enable
cfg.CacheBehaviorConfig.PrefetchThreshold = threshold
cfg.CacheBehaviorConfig.PrefetchCount = count
return nil
}
}
// WithAdaptiveTTL configures adaptive TTL settings.
func WithAdaptiveTTL(enable bool, minTTL, maxTTL, adjustInterval time.Duration) Option {
return func(cfg *config.Config) error {
cfg.CacheBehaviorConfig.EnableAdaptiveTTL = enable
cfg.CacheBehaviorConfig.AdaptiveTTLSettings.MinTTL = minTTL
cfg.CacheBehaviorConfig.AdaptiveTTLSettings.MaxTTL = maxTTL
cfg.CacheBehaviorConfig.AdaptiveTTLSettings.TTLAdjustInterval = adjustInterval
return nil
}
}
// WithCircuitBreaker configures circuit breaker settings.
func WithCircuitBreaker(maxRequests uint32, interval, timeout time.Duration) Option {
return func(cfg *config.Config) error {
cfg.ResilienceConfig.GlobalCircuitBreaker.MaxRequests = maxRequests
cfg.ResilienceConfig.GlobalCircuitBreaker.Interval = interval
cfg.ResilienceConfig.GlobalCircuitBreaker.Timeout = timeout
return nil
}
}