-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcache.go
More file actions
108 lines (88 loc) · 2.3 KB
/
cache.go
File metadata and controls
108 lines (88 loc) · 2.3 KB
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
package main
import (
"encoding/json"
"strconv"
"sync"
"time"
"github.com/withObsrvr/terminal/models"
)
// LedgerCache provides in-memory caching for ledger queries
// This is primarily useful for local development when catalog is remote
type LedgerCache struct {
mu sync.RWMutex
entries map[string]*CacheEntry
ttl time.Duration
}
type CacheEntry struct {
Data []byte
ExpiresAt time.Time
}
// NewLedgerCache creates a new cache with specified TTL
func NewLedgerCache(ttl time.Duration) *LedgerCache {
return &LedgerCache{
entries: make(map[string]*CacheEntry),
ttl: ttl,
}
}
// Get retrieves cached ledgers by network and query params
func (c *LedgerCache) Get(network string, limit, offset int) ([]models.Ledger, bool) {
c.mu.RLock()
defer c.mu.RUnlock()
key := c.makeKey(network, limit, offset)
entry, exists := c.entries[key]
if !exists || time.Now().After(entry.ExpiresAt) {
return nil, false
}
var ledgers []models.Ledger
if err := json.Unmarshal(entry.Data, &ledgers); err != nil {
return nil, false
}
return ledgers, true
}
// Set stores ledgers in cache
func (c *LedgerCache) Set(network string, limit, offset int, ledgers []models.Ledger) {
c.mu.Lock()
defer c.mu.Unlock()
data, err := json.Marshal(ledgers)
if err != nil {
return
}
key := c.makeKey(network, limit, offset)
c.entries[key] = &CacheEntry{
Data: data,
ExpiresAt: time.Now().Add(c.ttl),
}
}
// Clear removes all cache entries for a network
func (c *LedgerCache) Clear(network string) {
c.mu.Lock()
defer c.mu.Unlock()
// Remove all entries starting with network prefix
for key := range c.entries {
if len(key) > len(network) && key[:len(network)] == network {
delete(c.entries, key)
}
}
}
// CleanExpired removes expired entries (call periodically)
func (c *LedgerCache) CleanExpired() {
c.mu.Lock()
defer c.mu.Unlock()
now := time.Now()
for key, entry := range c.entries {
if now.After(entry.ExpiresAt) {
delete(c.entries, key)
}
}
}
func (c *LedgerCache) makeKey(network string, limit, offset int) string {
return network + ":" + strconv.Itoa(limit) + ":" + strconv.Itoa(offset)
}
// CacheStats returns cache statistics
func (c *LedgerCache) Stats() map[string]int {
c.mu.RLock()
defer c.mu.RUnlock()
return map[string]int{
"total_entries": len(c.entries),
}
}