-
Notifications
You must be signed in to change notification settings - Fork 0
/
store_local.go
121 lines (97 loc) · 2.92 KB
/
store_local.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
package imagine
import (
"fmt"
"os"
"time"
"github.com/juju/errors"
)
// LocalStoreParams are the parameters for creating a new LocalStore
type LocalStoreParams struct {
// Path is the path to the directory where the files will be stored
Path string
// TTL is the time to live for the file in seconds
// This is to be set if you want to use this store as a caching mechanism
TTL time.Duration
}
// localStore is a Store implementation that uses the local filesystem
type localStore struct {
params *LocalStoreParams
closeCh chan struct{}
}
// ensure localStore implements Store
var _ Store = new(localStore)
func (l *localStore) Set(filename string, data []byte) error {
path := fmt.Sprintf("%s/%s", l.params.Path, filename)
err := os.WriteFile(path, data, 0644)
if err != nil {
return errors.Annotate(err, "storage.Set: could not write file")
}
return nil
}
func (l *localStore) Get(filename string) ([]byte, bool, error) {
path := fmt.Sprintf("%s/%s", l.params.Path, filename)
// check if file exists
_, err := os.Stat(path)
if os.IsNotExist(err) {
return nil, false, ErrKeyNotFound
}
dat, err := os.ReadFile(path)
if err != nil {
return nil, false, errors.Annotate(err, "storage.Get: could not read file")
}
return dat, true, nil
}
func (l *localStore) Delete(filename string) error {
path := fmt.Sprintf("%s/%s", l.params.Path, filename)
return errors.Annotate(os.Remove(path), "storage.Delete: could not delete file")
}
func (l *localStore) Close() error {
close(l.closeCh)
return nil
}
func (l *localStore) cleanup() {
if l.params.TTL == time.Duration(0) {
return
}
go func() {
ticker := time.NewTicker(l.params.TTL / 2)
for {
select {
case <-l.closeCh:
ticker.Stop()
return
case <-ticker.C:
// get all files in the directory
files, err := os.ReadDir(l.params.Path)
if err != nil {
continue
}
// delete files that are older than TTL
for _, file := range files {
info, err := file.Info()
if err != nil {
continue
}
if time.Since(info.ModTime()) > l.params.TTL {
os.Remove(file.Name())
}
}
}
}
}()
}
func NewLocalStorage(params LocalStoreParams) (Store, error) {
// create the directory if it doesn't exist
if _, err := os.Stat(params.Path); os.IsNotExist(err) {
err := os.Mkdir(params.Path, 0755)
if err != nil {
return nil, errors.Annotate(err, "storage.NewLocalStorage: could not create directory")
}
}
ls := &localStore{
params: ¶ms,
closeCh: make(chan struct{}),
}
ls.cleanup()
return ls, nil
}