/
cache.go
62 lines (53 loc) · 1.42 KB
/
cache.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
package storage
import (
"context"
"github.com/awakari/int-activitypub/model"
"github.com/hashicorp/golang-lru/v2/expirable"
"time"
)
type localCache struct {
stor Storage
cache *expirable.LRU[string, model.Source]
}
func NewLocalCache(stor Storage, size int, ttl time.Duration) Storage {
c := expirable.NewLRU[string, model.Source](size, nil, ttl)
return localCache{
stor: stor,
cache: c,
}
}
func (lc localCache) Close() error {
lc.cache.Purge()
return lc.stor.Close()
}
func (lc localCache) Create(ctx context.Context, src model.Source) (err error) {
err = lc.stor.Create(ctx, src)
if err == nil {
lc.cache.Add(src.ActorId, src)
}
return
}
func (lc localCache) Read(ctx context.Context, srcId string) (src model.Source, err error) {
var found bool
src, found = lc.cache.Get(srcId)
if !found {
src, err = lc.stor.Read(ctx, srcId)
}
return
}
func (lc localCache) Update(ctx context.Context, src model.Source) (err error) {
err = lc.stor.Update(ctx, src)
if err == nil {
lc.cache.Add(src.ActorId, src)
}
return
}
func (lc localCache) Delete(ctx context.Context, srcId, groupId, userId string) (err error) {
err = lc.stor.Delete(ctx, srcId, groupId, userId)
lc.cache.Remove(srcId)
return
}
func (lc localCache) List(ctx context.Context, filter model.Filter, limit uint32, cursor string, order model.Order) (page []string, err error) {
page, err = lc.stor.List(ctx, filter, limit, cursor, order)
return
}