File size: 6,609 Bytes
4b1daed
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
// Package cache provides multi-tier caching implementation with local LRU and Redis
package cache

import (
	"context"
	"crypto/sha256"
	"encoding/hex"
	"encoding/json"
	"sync"
	"time"

	"github.com/redis/go-redis/v9"
)

// MultiTierCache implements a two-tier caching system with local LRU and Redis
type MultiTierCache struct {
	local      *LRUCache
	redis      *redis.Client
	ttl        time.Duration
	metrics    *CacheMetrics
}

// CacheMetrics tracks cache performance
type CacheMetrics struct {
	mu          sync.RWMutex
	LocalHits   int64
	LocalMisses int64
	RedisHits   int64
	RedisMisses int64
}

// Config for cache initialization
type Config struct {
	RedisURL   string
	LocalSize  int
	TTL        time.Duration
	MaxRetries int
	PoolSize   int
}

// New creates a new multi-tier cache
func New(cfg Config) (*MultiTierCache, error) {
	// Parse Redis URL
	opt, err := redis.ParseURL(cfg.RedisURL)
	if err != nil {
		return nil, err
	}
	opt.MaxRetries = cfg.MaxRetries
	opt.PoolSize = cfg.PoolSize

	redisClient := redis.NewClient(opt)

	// Test Redis connection
	ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
	defer cancel()
	if err := redisClient.Ping(ctx).Err(); err != nil {
		// Redis not available, continue with local cache only
		redisClient = nil
	}

	return &MultiTierCache{
		local:   NewLRUCache(cfg.LocalSize),
		redis:   redisClient,
		ttl:     cfg.TTL,
		metrics: &CacheMetrics{},
	}, nil
}

// Get retrieves a value from cache, checking local first then Redis
func (c *MultiTierCache) Get(ctx context.Context, key string) ([]byte, error) {
	hashedKey := c.hashKey(key)

	// Check local cache first (sub-millisecond)
	if value, found := c.local.Get(hashedKey); found {
		c.metrics.mu.Lock()
		c.metrics.LocalHits++
		c.metrics.mu.Unlock()
		return value, nil
	}
	c.metrics.mu.Lock()
	c.metrics.LocalMisses++
	c.metrics.mu.Unlock()

	// Check Redis if available (1-5ms)
	if c.redis != nil {
		value, err := c.redis.Get(ctx, hashedKey).Bytes()
		if err == nil {
			c.metrics.mu.Lock()
			c.metrics.RedisHits++
			c.metrics.mu.Unlock()
			// Backfill local cache
			c.local.Set(hashedKey, value)
			return value, nil
		}
		if err != redis.Nil {
			// Log error but continue
		}
		c.metrics.mu.Lock()
		c.metrics.RedisMisses++
		c.metrics.mu.Unlock()
	}

	return nil, ErrCacheMiss
}

// Set stores a value in both cache tiers
func (c *MultiTierCache) Set(ctx context.Context, key string, value []byte, ttlSeconds int) error {
	hashedKey := c.hashKey(key)
	ttl := time.Duration(ttlSeconds) * time.Second
	if ttlSeconds == 0 {
		ttl = c.ttl
	}

	// Set in local cache
	c.local.Set(hashedKey, value)

	// Set in Redis if available
	if c.redis != nil {
		if err := c.redis.Set(ctx, hashedKey, value, ttl).Err(); err != nil {
			// Log error but don't fail - local cache is still valid
			return nil
		}
	}

	return nil
}

// Delete removes a value from both cache tiers
func (c *MultiTierCache) Delete(ctx context.Context, key string) error {
	hashedKey := c.hashKey(key)

	// Delete from local cache
	c.local.Delete(hashedKey)

	// Delete from Redis if available
	if c.redis != nil {
		if err := c.redis.Del(ctx, hashedKey).Err(); err != nil {
			return err
		}
	}

	return nil
}

// GetJSON retrieves and unmarshals a JSON value from cache
func (c *MultiTierCache) GetJSON(ctx context.Context, key string, v interface{}) error {
	data, err := c.Get(ctx, key)
	if err != nil {
		return err
	}
	return json.Unmarshal(data, v)
}

// SetJSON marshals and stores a JSON value in cache
func (c *MultiTierCache) SetJSON(ctx context.Context, key string, v interface{}, ttlSeconds int) error {
	data, err := json.Marshal(v)
	if err != nil {
		return err
	}
	return c.Set(ctx, key, data, ttlSeconds)
}

// GetMetrics returns cache performance metrics
func (c *MultiTierCache) GetMetrics() CacheMetrics {
	c.metrics.mu.RLock()
	defer c.metrics.mu.RUnlock()
	return CacheMetrics{
		LocalHits:   c.metrics.LocalHits,
		LocalMisses: c.metrics.LocalMisses,
		RedisHits:   c.metrics.RedisHits,
		RedisMisses: c.metrics.RedisMisses,
	}
}

// Close closes the cache connections
func (c *MultiTierCache) Close() error {
	if c.redis != nil {
		return c.redis.Close()
	}
	return nil
}

func (c *MultiTierCache) hashKey(key string) string {
	hash := sha256.Sum256([]byte(key))
	return "amani:" + hex.EncodeToString(hash[:16])
}

// ErrCacheMiss indicates the key was not found in cache
var ErrCacheMiss = &CacheMissError{}

// CacheMissError represents a cache miss
type CacheMissError struct{}

func (e *CacheMissError) Error() string {
	return "cache miss"
}

// LRUCache implements a simple LRU cache
type LRUCache struct {
	mu       sync.RWMutex
	capacity int
	items    map[string]*lruItem
	head     *lruItem
	tail     *lruItem
}

type lruItem struct {
	key   string
	value []byte
	prev  *lruItem
	next  *lruItem
}

// NewLRUCache creates a new LRU cache with the given capacity
func NewLRUCache(capacity int) *LRUCache {
	return &LRUCache{
		capacity: capacity,
		items:    make(map[string]*lruItem),
	}
}

// Get retrieves a value from the LRU cache
func (c *LRUCache) Get(key string) ([]byte, bool) {
	c.mu.Lock()
	defer c.mu.Unlock()

	item, found := c.items[key]
	if !found {
		return nil, false
	}

	// Move to front (most recently used)
	c.moveToFront(item)
	return item.value, true
}

// Set stores a value in the LRU cache
func (c *LRUCache) Set(key string, value []byte) {
	c.mu.Lock()
	defer c.mu.Unlock()

	// Check if item exists
	if item, found := c.items[key]; found {
		item.value = value
		c.moveToFront(item)
		return
	}

	// Create new item
	item := &lruItem{key: key, value: value}
	c.items[key] = item
	c.addToFront(item)

	// Evict if over capacity
	if len(c.items) > c.capacity {
		c.evictLRU()
	}
}

// Delete removes a value from the LRU cache
func (c *LRUCache) Delete(key string) {
	c.mu.Lock()
	defer c.mu.Unlock()

	if item, found := c.items[key]; found {
		c.removeItem(item)
		delete(c.items, key)
	}
}

func (c *LRUCache) moveToFront(item *lruItem) {
	if item == c.head {
		return
	}
	c.removeItem(item)
	c.addToFront(item)
}

func (c *LRUCache) addToFront(item *lruItem) {
	item.prev = nil
	item.next = c.head
	if c.head != nil {
		c.head.prev = item
	}
	c.head = item
	if c.tail == nil {
		c.tail = item
	}
}

func (c *LRUCache) removeItem(item *lruItem) {
	if item.prev != nil {
		item.prev.next = item.next
	} else {
		c.head = item.next
	}
	if item.next != nil {
		item.next.prev = item.prev
	} else {
		c.tail = item.prev
	}
}

func (c *LRUCache) evictLRU() {
	if c.tail == nil {
		return
	}
	delete(c.items, c.tail.key)
	c.removeItem(c.tail)
}