-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathfilecache.go
More file actions
177 lines (145 loc) · 4.15 KB
/
filecache.go
File metadata and controls
177 lines (145 loc) · 4.15 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
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
// filecache is a simple local file-based cache
package filecache
import (
"encoding/json"
"os"
"path/filepath"
"time"
"github.com/gofrs/flock"
"github.com/pkg/errors"
"go.jetify.com/pkg/cachehash"
)
var (
NotFound = errors.New("not found")
Expired = errors.New("expired")
)
type Cache[T any] struct {
domain string
cacheDir string
}
type data[T any] struct {
Val T
Exp time.Time
}
type Option[T any] func(*Cache[T])
func New[T any](domain string, opts ...Option[T]) *Cache[T] {
result := &Cache[T]{domain: domain}
var err error
result.cacheDir, err = os.UserCacheDir()
if err != nil {
result.cacheDir = "~/.cache"
}
for _, opt := range opts {
opt(result)
}
return result
}
func WithCacheDir[T any](dir string) Option[T] {
return func(c *Cache[T]) {
c.cacheDir = dir
}
}
// Set stores a value in the cache with the given key and expiration duration.
func (c *Cache[T]) Set(key string, val T, dur time.Duration) error {
d, err := json.Marshal(data[T]{Val: val, Exp: time.Now().Add(dur)})
if err != nil {
return errors.WithStack(err)
}
// Acquire exclusive lock to prevent concurrent writes from corrupting the file
lock := flock.New(c.lockfile())
if err := lock.Lock(); err != nil {
return errors.WithStack(err)
}
defer lock.Unlock()
return errors.WithStack(os.WriteFile(c.filename(key), d, 0o644))
}
// SetWithTime is like Set but it allows the caller to specify the expiration
// time of the value.
func (c *Cache[T]) SetWithTime(key string, val T, t time.Time) error {
d, err := json.Marshal(data[T]{Val: val, Exp: t})
if err != nil {
return errors.WithStack(err)
}
// Acquire exclusive lock to prevent concurrent writes from corrupting the file
lock := flock.New(c.lockfile())
if err := lock.Lock(); err != nil {
return errors.WithStack(err)
}
defer lock.Unlock()
return errors.WithStack(os.WriteFile(c.filename(key), d, 0o644))
}
// Get retrieves a value from the cache with the given key.
func (c *Cache[T]) Get(key string) (T, error) {
path := c.filename(key)
resultData := data[T]{}
// Acquire shared lock before checking file existence to prevent TOCTOU race
lock := flock.New(c.lockfile())
if err := lock.RLock(); err != nil {
return resultData.Val, errors.WithStack(err)
}
defer lock.Unlock()
if _, err := os.Stat(path); errors.Is(err, os.ErrNotExist) {
return resultData.Val, NotFound
}
content, err := os.ReadFile(path)
if err != nil {
return resultData.Val, errors.WithStack(err)
}
if err := json.Unmarshal(content, &resultData); err != nil {
return resultData.Val, errors.WithStack(err)
}
if time.Now().After(resultData.Exp) {
return resultData.Val, Expired
}
return resultData.Val, nil
}
// GetOrSet is a convenience method that gets the value from the cache if it
// exists, otherwise it calls the provided function to get the value and sets
// it in the cache.
// If the function returns an error, the error is returned and the value is not
// cached.
func (c *Cache[T]) GetOrSet(
key string,
f func() (T, time.Duration, error),
) (T, error) {
if val, err := c.Get(key); err == nil || !IsCacheMiss(err) {
return val, err
}
val, dur, err := f()
if err != nil {
return val, err
}
return val, c.Set(key, val, dur)
}
// GetOrSetWithTime is like GetOrSet but it allows the caller to specify the
// expiration time of the value.
func (c *Cache[T]) GetOrSetWithTime(
key string,
f func() (T, time.Time, error),
) (T, error) {
if val, err := c.Get(key); err == nil || !IsCacheMiss(err) {
return val, err
}
val, t, err := f()
if err != nil {
return val, err
}
return val, c.SetWithTime(key, val, t)
}
func (c *Cache[T]) Clear() error {
return errors.WithStack(os.RemoveAll(filepath.Join(c.cacheDir, c.domain)))
}
// IsCacheMiss returns true if the error is NotFound or Expired.
func IsCacheMiss(err error) bool {
return errors.Is(err, NotFound) || errors.Is(err, Expired)
}
func (c *Cache[T]) filename(key string) string {
dir := filepath.Join(c.cacheDir, c.domain)
_ = os.MkdirAll(dir, 0o755)
return filepath.Join(dir, cachehash.Slug(key))
}
func (c *Cache[T]) lockfile() string {
dir := filepath.Join(c.cacheDir, c.domain)
_ = os.MkdirAll(dir, 0o755)
return filepath.Join(dir, ".lock")
}