-
Notifications
You must be signed in to change notification settings - Fork 62
/
record.go
99 lines (85 loc) · 1.76 KB
/
record.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
package record
import (
"sync"
"time"
"github.com/ac0d3r/hyuga/pkg/event"
lru "github.com/hashicorp/golang-lru/v2"
"github.com/patrickmn/go-cache"
"github.com/sirupsen/logrus"
)
const (
defaultCacheExpiration = 6 * time.Hour
defaultCacheCleanup = 10 * time.Minute
defaultCacheSize = 50
)
type Recorder struct {
pool *cache.Cache
eventbus *event.EventBus
}
func NewRecorder(eventbus *event.EventBus) *Recorder {
c := cache.New(defaultCacheExpiration, defaultCacheCleanup)
c.OnEvicted(func(key string, v any) {
logrus.Debugf("[db][recorder] key:%s deleted", key)
l, ok := v.(*lru.Cache[int, any])
if ok {
putlru(l)
}
})
return &Recorder{
pool: c,
eventbus: eventbus,
}
}
func (r *Recorder) Record(userid string, v any) error {
if r.eventbus != nil {
r.eventbus.Publish(userid, v)
}
lru_, ok := r.pool.Get(userid)
if !ok {
l := getlru()
l.Add(0, v)
r.pool.Set(userid, l, cache.DefaultExpiration)
return nil
} else {
l := lru_.(*lru.Cache[int, any])
key := l.Len()
if key >= defaultCacheSize {
key = l.Keys()[l.Len()-1]
key++
}
l.Add(key, v)
r.pool.Set(userid, l, cache.DefaultExpiration)
}
return nil
}
func (r *Recorder) Get(userid string) ([]any, error) {
lru_, ok := r.pool.Get(userid)
if !ok {
return nil, nil
}
l := lru_.(*lru.Cache[int, any])
if l.Len() == 0 {
return nil, nil
}
res := make([]any, 0, l.Len())
for _, key := range l.Keys() {
v, ok := l.Get(key)
if ok {
res = append(res, v)
}
}
return res, nil
}
var lruPool = sync.Pool{New: func() any {
l, _ := lru.New[int, any](defaultCacheSize)
return l
}}
func getlru() *lru.Cache[int, any] {
return lruPool.Get().(*lru.Cache[int, any])
}
func putlru(l *lru.Cache[int, any]) {
if l != nil {
l.Purge()
lruPool.Put(l)
}
}