-
Notifications
You must be signed in to change notification settings - Fork 351
/
file_tracker.go
67 lines (58 loc) · 1.2 KB
/
file_tracker.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
package pyramid
import (
"sync"
"github.com/treeverse/lakefs/pkg/pyramid/params"
)
// fileTracker tracks file open requests in TierFS to avoid race conditions with cache rejection/eviction
type fileTracker struct {
refMap map[string]*tracked
mu sync.Mutex
delete deleteCallback
}
type deleteCallback func(path params.RelativePath)
type tracked struct {
ref int
deleted bool
}
func NewFileTracker(delete deleteCallback) *fileTracker {
return &fileTracker{
refMap: map[string]*tracked{},
delete: delete,
}
}
func (t *fileTracker) Open(path params.RelativePath) func() {
t.mu.Lock()
defer t.mu.Unlock()
if val, ok := t.refMap[string(path)]; ok {
val.ref++
} else {
t.refMap[string(path)] = &tracked{
ref: 1,
}
}
return func() {
t.close(path)
}
}
func (t *fileTracker) close(path params.RelativePath) {
t.mu.Lock()
defer t.mu.Unlock()
if val, ok := t.refMap[string(path)]; ok {
val.ref--
if val.ref == 0 {
delete(t.refMap, string(path))
if val.deleted {
t.delete(path)
}
}
}
}
func (t *fileTracker) Delete(path params.RelativePath) {
t.mu.Lock()
defer t.mu.Unlock()
if val, ok := t.refMap[string(path)]; ok {
val.deleted = true
} else {
t.delete(path)
}
}