-
Notifications
You must be signed in to change notification settings - Fork 34
/
fscache.go
373 lines (316 loc) · 8.37 KB
/
fscache.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
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
package fscache
import (
"fmt"
"io"
"os"
"sync"
"sync/atomic"
"time"
"github.com/djherbis/stream"
)
// Cache works like a concurrent-safe map for streams.
type Cache interface {
// Get manages access to the streams in the cache.
// If the key does not exist, w != nil and you can start writing to the stream.
// If the key does exist, w == nil.
// r will always be non-nil as long as err == nil and you must close r when you're done reading.
// Get can be called concurrently, and writing and reading is concurrent safe.
Get(key string) (ReadAtCloser, io.WriteCloser, error)
// Remove deletes the stream from the cache, blocking until the underlying
// file can be deleted (all active streams finish with it).
// It is safe to call Remove concurrently with Get.
Remove(key string) error
// Exists checks if a key is in the cache.
// It is safe to call Exists concurrently with Get.
Exists(key string) bool
// Clean will empty the cache and delete the cache folder.
// Clean is not safe to call while streams are being read/written.
Clean() error
}
// FSCache is a Cache which uses a Filesystem to read/write cached data.
type FSCache struct {
mu sync.RWMutex
files map[string]fileStream
km func(string) string
fs FileSystem
haunter Haunter
}
// SetKeyMapper will use the given function to transform any given Cache key into the result of km(key).
// This means that internally, the cache will only track km(key), and forget the original key. The consequences
// of this are that Enumerate will return km(key) instead of key, and Filesystem will give km(key) to Create
// and expect Reload() to return km(key).
// The purpose of this function is so that the internally managed key can be converted to a string that is
// allowed as a filesystem path.
func (c *FSCache) SetKeyMapper(km func(string) string) *FSCache {
c.mu.Lock()
defer c.mu.Unlock()
c.km = km
return c
}
func (c *FSCache) mapKey(key string) string {
if c.km == nil {
return key
}
return c.km(key)
}
// ReadAtCloser is an io.ReadCloser, and an io.ReaderAt. It supports both so that Range
// Requests are possible.
type ReadAtCloser interface {
io.ReadCloser
io.ReaderAt
}
type fileStream interface {
next() (*CacheReader, error)
InUse() bool
io.WriteCloser
remove() error
Name() string
}
// New creates a new Cache using NewFs(dir, perms).
// expiry is the duration after which an un-accessed key will be removed from
// the cache, a zero value expiro means never expire.
func New(dir string, perms os.FileMode, expiry time.Duration) (*FSCache, error) {
fs, err := NewFs(dir, perms)
if err != nil {
return nil, err
}
var grim Reaper
if expiry > 0 {
grim = &reaper{
expiry: expiry,
period: expiry,
}
}
return NewCache(fs, grim)
}
// NewCache creates a new Cache based on FileSystem fs.
// fs.Files() are loaded using the name they were created with as a key.
// Reaper is used to determine when files expire, nil means never expire.
func NewCache(fs FileSystem, grim Reaper) (*FSCache, error) {
if grim != nil {
return NewCacheWithHaunter(fs, NewReaperHaunterStrategy(grim))
}
return NewCacheWithHaunter(fs, nil)
}
// NewCacheWithHaunter create a new Cache based on FileSystem fs.
// fs.Files() are loaded using the name they were created with as a key.
// Haunter is used to determine when files expire, nil means never expire.
func NewCacheWithHaunter(fs FileSystem, haunter Haunter) (*FSCache, error) {
c := &FSCache{
files: make(map[string]fileStream),
haunter: haunter,
fs: fs,
}
err := c.load()
if err != nil {
return nil, err
}
if haunter != nil {
c.scheduleHaunt()
}
return c, nil
}
func (c *FSCache) scheduleHaunt() {
c.haunt()
time.AfterFunc(c.haunter.Next(), c.scheduleHaunt)
}
func (c *FSCache) haunt() {
c.mu.Lock()
defer c.mu.Unlock()
c.haunter.Haunt(&accessor{c: c})
}
func (c *FSCache) load() error {
c.mu.Lock()
defer c.mu.Unlock()
return c.fs.Reload(func(key, name string) {
c.files[key] = c.oldFile(name)
})
}
// Exists returns true iff this key is in the Cache (may not be finished streaming).
func (c *FSCache) Exists(key string) bool {
c.mu.RLock()
defer c.mu.RUnlock()
_, ok := c.files[c.mapKey(key)]
return ok
}
// Get obtains a ReadAtCloser for the given key, and may return a WriteCloser to write the original cache data
// if this is a cache-miss.
func (c *FSCache) Get(key string) (r ReadAtCloser, w io.WriteCloser, err error) {
c.mu.RLock()
key = c.mapKey(key)
f, ok := c.files[key]
if ok {
r, err = f.next()
c.mu.RUnlock()
return r, nil, err
}
c.mu.RUnlock()
c.mu.Lock()
defer c.mu.Unlock()
f, ok = c.files[key]
if ok {
r, err = f.next()
return r, nil, err
}
f, err = c.newFile(key)
if err != nil {
return nil, nil, err
}
r, err = f.next()
if err != nil {
_ = f.Close()
_ = c.fs.Remove(f.Name())
return nil, nil, err
}
c.files[key] = f
return r, f, err
}
// Remove removes the specified key from the cache.
func (c *FSCache) Remove(key string) error {
c.mu.Lock()
key = c.mapKey(key)
f, ok := c.files[key]
delete(c.files, key)
c.mu.Unlock()
if ok {
return f.remove()
}
return nil
}
// Clean resets the cache removing all keys and data.
func (c *FSCache) Clean() error {
c.mu.Lock()
defer c.mu.Unlock()
c.files = make(map[string]fileStream)
return c.fs.RemoveAll()
}
type accessor struct {
c *FSCache
}
func (a *accessor) Stat(name string) (FileInfo, error) {
return a.c.fs.Stat(name)
}
func (a *accessor) EnumerateEntries(enumerator func(key string, e Entry) bool) {
for k, f := range a.c.files {
if !enumerator(k, Entry{name: f.Name(), inUse: f.InUse()}) {
break
}
}
}
func (a *accessor) RemoveFile(key string) {
key = a.c.mapKey(key)
f, ok := a.c.files[key]
delete(a.c.files, key)
if ok {
_ = a.c.fs.Remove(f.Name())
}
}
type cachedFile struct {
handleCounter
stream *stream.Stream
}
func (c *FSCache) newFile(name string) (fileStream, error) {
s, err := stream.NewStream(name, c.fs)
if err != nil {
return nil, err
}
cf := &cachedFile{
stream: s,
}
cf.inc()
return cf, nil
}
func (c *FSCache) oldFile(name string) fileStream {
return &reloadedFile{
fs: c.fs,
name: name,
}
}
type reloadedFile struct {
handleCounter
fs FileSystem
name string
io.WriteCloser // nop Write & Close methods. will never be called.
}
func (f *reloadedFile) Name() string { return f.name }
func (f *reloadedFile) remove() error {
f.waitUntilFree()
return f.fs.Remove(f.name)
}
func (f *reloadedFile) next() (*CacheReader, error) {
r, err := f.fs.Open(f.name)
if err == nil {
f.inc()
}
return &CacheReader{
ReadAtCloser: r,
cnt: &f.handleCounter,
}, err
}
func (f *cachedFile) Name() string { return f.stream.Name() }
func (f *cachedFile) remove() error { return f.stream.Remove() }
func (f *cachedFile) next() (*CacheReader, error) {
reader, err := f.stream.NextReader()
if err != nil {
return nil, err
}
f.inc()
return &CacheReader{
ReadAtCloser: reader,
cnt: &f.handleCounter,
}, nil
}
func (f *cachedFile) Write(p []byte) (int, error) {
return f.stream.Write(p)
}
func (f *cachedFile) Close() error {
defer f.dec()
return f.stream.Close()
}
// CacheReader is a ReadAtCloser for a Cache key that also tracks open readers.
type CacheReader struct {
ReadAtCloser
cnt *handleCounter
}
// Close frees the underlying ReadAtCloser and updates the open reader counter.
func (r *CacheReader) Close() error {
defer r.cnt.dec()
return r.ReadAtCloser.Close()
}
// Size returns the current size of the stream being read, the boolean it
// returns is true iff the stream is done being written (otherwise Size may change).
// An error is returned if the Size fails to be computed or is not supported
// by the underlying filesystem.
func (r *CacheReader) Size() (int64, bool, error) {
switch v := r.ReadAtCloser.(type) {
case *stream.Reader:
size, done := v.Size()
return size, done, nil
case interface{ Stat() (os.FileInfo, error) }:
fi, err := v.Stat()
if err != nil {
return 0, false, err
}
return fi.Size(), true, nil
default:
return 0, false, fmt.Errorf("reader does not support stat")
}
}
type handleCounter struct {
cnt int64
grp sync.WaitGroup
}
func (h *handleCounter) inc() {
h.grp.Add(1)
atomic.AddInt64(&h.cnt, 1)
}
func (h *handleCounter) dec() {
atomic.AddInt64(&h.cnt, -1)
h.grp.Done()
}
func (h *handleCounter) InUse() bool {
return atomic.LoadInt64(&h.cnt) > 0
}
func (h *handleCounter) waitUntilFree() {
h.grp.Wait()
}