-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathcache.go
More file actions
100 lines (81 loc) · 1.59 KB
/
cache.go
File metadata and controls
100 lines (81 loc) · 1.59 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
package main
import (
"errors"
"io"
"sync"
"time"
"golang.org/x/net/context"
"github.com/jacobsa/fuse/fuseops"
)
type cacheKey struct {
Inode fuseops.InodeID
Offset int64
}
type cacheEntry struct {
rd io.Reader
t time.Time
}
// Cache holds a list of recently read files.
type Cache struct {
entries map[cacheKey]cacheEntry
m sync.Mutex
}
func newCache(ctx context.Context) *Cache {
c := &Cache{
entries: make(map[cacheKey]cacheEntry),
}
go c.cleanup(ctx)
return c
}
// Get retrieves and removes an entry from the cache.
func (c *Cache) Get(inode fuseops.InodeID, off int64) (io.Reader, error) {
c.m.Lock()
defer c.m.Unlock()
key := cacheKey{Inode: inode, Offset: off}
entry, ok := c.entries[key]
if !ok {
return nil, errors.New("not found")
}
delete(c.entries, key)
return entry.rd, nil
}
// Put stores an entry in the cache.
func (c *Cache) Put(inode fuseops.InodeID, off int64, rd io.Reader) {
c.m.Lock()
defer c.m.Unlock()
key := cacheKey{Inode: inode, Offset: off}
_, ok := c.entries[key]
if ok {
return
}
entry := cacheEntry{
rd: rd,
t: time.Now(),
}
c.entries[key] = entry
}
const (
cacheTimeout = 20 * time.Second
cacheTicker = 5 * time.Second
)
// cleanup removes old entries from the cache.
func (c *Cache) cleanup(ctx context.Context) {
ticker := time.NewTicker(cacheTicker)
defer ticker.Stop()
for {
select {
case <-ticker.C:
n := 0
c.m.Lock()
for key, entry := range c.entries {
if time.Since(entry.t) > cacheTimeout {
delete(c.entries, key)
n++
}
}
c.m.Unlock()
case <-ctx.Done():
return
}
}
}