-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathquerier_cache_ext.go
More file actions
68 lines (55 loc) · 1.46 KB
/
querier_cache_ext.go
File metadata and controls
68 lines (55 loc) · 1.46 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
package pgxcache
import (
"context"
"fmt"
"time"
"github.com/dgraph-io/ristretto/v2"
)
var _ QueryCacher = &MemoryQueryCacher{}
// MemoryQueryCacher is a simple in-memory cache implementation.
type MemoryQueryCacher struct {
cache *ristretto.Cache[string, []byte]
}
// NewMemoryQueryCacher creates a new MemoryCacher.
func NewMemoryQueryCacher() *MemoryQueryCacher {
cache, _ := ristretto.NewCache(&ristretto.Config[string, []byte]{
MaxCost: 1 << 30,
NumCounters: 1e7,
BufferItems: 64,
})
return &MemoryQueryCacher{
cache: cache,
}
}
// Get implements Cacher.
func (x *MemoryQueryCacher) Get(_ context.Context, key *QueryKey) (*QueryItem, error) {
// get the data from the cache
data, ok := x.cache.Get(key.String())
if !ok {
return nil, nil
}
item := &QueryItem{}
// unmarshal the data into the item
if err := item.UnmarshalText(data); err != nil {
return nil, err
}
return item, nil
}
// Set implements Cacher.
func (x *MemoryQueryCacher) Set(_ context.Context, key *QueryKey, item *QueryItem, lifetime time.Duration) error {
// marshal the item into bytes
data, err := item.MarshalText()
if err != nil {
return err
}
// using # of rows as cost
if ok := x.cache.SetWithTTL(key.String(), data, int64(len(data)), lifetime); !ok {
return fmt.Errorf("unable to set the item for key: %v", key.String())
}
return nil
}
// Reset resets the cache.
func (x *MemoryQueryCacher) Reset(_ context.Context) error {
x.cache.Clear()
return nil
}