-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathref_counted_file_remover.go
108 lines (84 loc) · 1.92 KB
/
ref_counted_file_remover.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
package ioutils
import (
"fmt"
"io"
"os"
"sync"
"sync/atomic"
)
type RefCountedFileRemover struct {
path string
refCount int
refCountMutex sync.Mutex
totalClonedCount int64
OnRemoveError func(path string, err error)
}
func NewRefCountedFileRemover(path string) *RefCountedFileRemover {
return &RefCountedFileRemover{
path: path,
refCount: 0,
}
}
func (r *RefCountedFileRemover) TotalClonedCount() int64 {
return atomic.LoadInt64(&r.totalClonedCount)
}
func (r *RefCountedFileRemover) Open() (*RefCountedFileRemoveReader, error) {
file, err := os.Open(r.path)
if err != nil {
return nil, fmt.Errorf("failed to open dest path: %w", err)
}
r.refCountMutex.Lock()
r.refCount++
r.refCountMutex.Unlock()
atomic.AddInt64(&r.totalClonedCount, 1)
reader := &RefCountedFileRemoveReader{
File: file,
remover: r,
isDereferenced: false,
}
return reader, nil
}
func (r *RefCountedFileRemover) derefAndRemoveIfUnused() {
r.refCountMutex.Lock()
r.refCount--
isUnused := r.refCount == 0
r.refCountMutex.Unlock()
if isUnused {
err := os.Remove(r.path)
if err != nil {
if r.OnRemoveError != nil {
r.OnRemoveError(r.path, err)
}
}
}
}
type RefCountedFileRemoveReader struct {
*os.File
remover *RefCountedFileRemover
isDereferenced bool
onAfterClose func()
}
func (r *RefCountedFileRemoveReader) Clone() (io.ReadCloser, error) {
return r.remover.Open()
}
func (r *RefCountedFileRemoveReader) deref() {
if r.isDereferenced {
return
}
r.isDereferenced = true
r.remover.derefAndRemoveIfUnused()
}
func (r *RefCountedFileRemoveReader) afterClose() {
if r.onAfterClose != nil {
r.onAfterClose()
}
r.deref()
}
func (r *RefCountedFileRemoveReader) Close() error {
defer r.afterClose()
return r.File.Close()
}
func (r *RefCountedFileRemoveReader) SetOnAfterClose(onAfterClose func()) {
r.onAfterClose = onAfterClose
}
var _ ReadCloseCloner = (*RefCountedFileRemoveReader)(nil)