-
Notifications
You must be signed in to change notification settings - Fork 2
/
file.go
340 lines (303 loc) · 7.52 KB
/
file.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
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
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
package cachita
import (
"fmt"
"io"
"io/ioutil"
"os"
"path/filepath"
"sync"
"time"
"github.com/vmihailenco/msgpack"
)
const FileIndex = "github.com/gadelkareem/cachita/file-index"
var fCache Cache
type file struct {
dir string
ttl time.Duration
i *fileIndex
}
type fileIndex struct {
recordsMu sync.RWMutex
records map[string]time.Time
tagsMu sync.Mutex
tags map[string][]string
path string
}
func File() (Cache, error) {
if fCache == nil {
path, err := filepath.Abs(filepath.Dir(os.Args[0]))
if err != nil {
return nil, err
}
path = filepath.Join(path, "tmp/file-cache")
fCache, err = NewFileCache(path, 24*time.Hour, 5*time.Minute)
if err != nil {
return nil, err
}
}
return fCache, nil
}
func NewFileCache(dir string, ttl, tickerTtl time.Duration) (Cache, error) {
var (
err error
i *fileIndex
)
i, err = newIndex(dir, ttl)
if err != nil {
return nil, err
}
c := &file{
dir: dir,
ttl: ttl,
i: i,
}
if tickerTtl != 0 {
runEvery(tickerTtl, func() {
c.deleteExpired()
})
}
return c, nil
}
func (c *file) Exists(key string) bool {
err := c.i.check(Id(key))
return err == nil
}
func (c *file) Get(key string, i interface{}) error {
id := Id(key)
if err := c.i.check(id); err != nil {
return err
}
return readData(c.path(id), i)
}
func (c *file) Put(key string, i interface{}, ttl time.Duration) error {
id := Id(key)
c.i.add(id, expiredAt(ttl, c.ttl))
return writeData(c.path(id), i)
}
func (c *file) Incr(key string, ttl time.Duration) (int64, error) {
id := Id(key)
c.i.checkOrAdd(id, expiredAt(ttl, c.ttl))
var n int64
path := c.path(id)
err := readData(path, &n)
if err != nil && !IsErrorOk(err) {
return 0, err
}
n++
return n, writeData(path, &n)
}
func (c *file) Invalidate(key string) error {
id := Id(key)
c.i.remove(id)
err := os.Remove(c.path(id))
if os.IsNotExist(err) {
return ErrNotFound
}
return err
}
func (c *file) path(id string) string {
return filepath.Join(c.dir, string(id[0]), string(id[1]), id)
}
func (c *file) deleteExpired() {
expired := c.i.expiredRecords()
for _, id := range expired {
_ = os.Remove(c.path(id))
}
}
func (c *file) InvalidateMulti(keys ...string) (err error) {
var ids []string
for _, key := range keys {
id := Id(key)
err = os.Remove(c.path(id))
if err != nil && !isNotFound(err) {
return
}
}
c.i.removeMulti(ids...)
return
}
// tags are only managed via the index
func (c *file) Tag(key string, tags ...string) error {
tags = uniqueTags(tags)
c.i.tag(Id(key), tags...)
return nil
}
func (c *file) InvalidateTags(tags ...string) (err error) {
tags = uniqueTags(tags)
ids := c.i.removeTags(tags...)
for _, id := range ids {
err = os.Remove(c.path(id))
if err != nil && !isNotFound(err) {
return
}
}
c.i.removeMulti(ids...)
return nil
}
// ----------------------- fileIndex
func newIndex(dir string, ttl time.Duration) (i *fileIndex, err error) {
i = &fileIndex{path: filepath.Join(dir, Id(FileIndex))}
i.records = make(map[string]time.Time)
i.tags = make(map[string][]string)
err = readData(i.path, &i.records)
if err != nil && err != ErrNotFound {
return
}
var (
currentDir string
files []os.FileInfo
)
i.recordsMu.Lock()
defer i.recordsMu.Unlock()
characters := "0123456789abcdef"
for _, char1 := range characters {
for _, char2 := range characters {
currentDir = filepath.Join(dir, string(char1), string(char2))
if ok, _ := exists(currentDir); !ok {
err = os.MkdirAll(currentDir, os.ModePerm)
if err != nil {
return
}
}
files, err = ioutil.ReadDir(currentDir)
if err != nil {
return
}
for _, f := range files {
if f.IsDir() {
continue
}
if _, exists := i.records[f.Name()]; exists {
continue
}
expiredAt := f.ModTime().Add(ttl)
if expiredAt.After(time.Now()) {
i.records[f.Name()] = expiredAt
}
}
}
}
err = writeData(i.path, &i.records)
if err != nil {
return nil, err
}
return i, nil
}
func (i *fileIndex) check(id string) error {
i.recordsMu.RLock()
defer i.recordsMu.RUnlock()
expiredAt, exists := i.records[id]
if !exists {
return ErrNotFound
}
if expiredAt.Before(time.Now()) {
return ErrExpired
}
return nil
}
func (i *fileIndex) expiredRecords() []string {
i.recordsMu.Lock()
defer i.recordsMu.Unlock()
var (
expired []string
records = make(map[string]time.Time)
)
for id, expiredAt := range i.records {
if expiredAt.Before(time.Now()) {
expired = append(expired, id)
continue
}
records[id] = expiredAt
}
i.records = records
err := writeData(i.path, &i.records)
if err != nil {
fmt.Printf("cachita: error writing index file: %v", err)
}
return expired
}
func (i *fileIndex) add(id string, expiredAt time.Time) {
i.recordsMu.Lock()
defer i.recordsMu.Unlock()
i.records[id] = expiredAt
return
}
func (i *fileIndex) checkOrAdd(id string, expiredAt time.Time) {
i.recordsMu.Lock()
defer i.recordsMu.Unlock()
exp, k := i.records[id]
if !k || exp.Before(time.Now()) {
i.records[id] = expiredAt
}
}
func (i *fileIndex) remove(id string) {
i.recordsMu.Lock()
defer i.recordsMu.Unlock()
delete(i.records, id)
}
func (i *fileIndex) removeMulti(ids ...string) {
i.recordsMu.Lock()
defer i.recordsMu.Unlock()
for _, id := range ids {
delete(i.records, id)
}
}
func (i *fileIndex) tag(id string, tags ...string) {
tags = uniqueTags(tags)
i.tagsMu.Lock()
defer i.tagsMu.Unlock()
for _, t := range tags {
if inArr(i.tags[t], id) {
continue
}
i.tags[t] = append(i.tags[t], id)
}
}
func (i *fileIndex) removeTags(tags ...string) (ids []string) {
tags = uniqueTags(tags)
i.tagsMu.Lock()
for _, t := range tags {
ids = append(ids, i.tags[t]...)
delete(i.tags, t)
}
i.tagsMu.Unlock()
return
}
// --------------------
func exists(path string) (bool, error) {
_, err := os.Stat(path)
if err == nil {
return true, nil
}
if isNotFound(err) {
return false, nil
}
return false, err
}
func readData(path string, i interface{}) error {
data, err := ioutil.ReadFile(path)
if err != nil {
if isNotFound(err) {
return ErrNotFound
}
return err
}
err = msgpack.Unmarshal(data, i)
if err != nil {
if err == io.EOF {
return ErrNotFound
}
return err
}
return nil
}
func writeData(path string, i interface{}) error {
data, err := msgpack.Marshal(i)
if err != nil {
return err
}
return ioutil.WriteFile(path, data, 0666)
}
func isNotFound(e error) bool {
return os.IsNotExist(e) || e == io.EOF
}