-
Notifications
You must be signed in to change notification settings - Fork 0
/
store.go
274 lines (220 loc) · 5.25 KB
/
store.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
package vai
import (
"crypto/sha256"
"encoding/json"
"errors"
"fmt"
"io"
"os"
"path/filepath"
"sync"
)
// ErrHashMismatch is returned when the hash of the stored file does not match the hash in the index.
var ErrHashMismatch = fmt.Errorf("hash mismatch")
// IsHashMismatch returns true if the error is a hash mismatch error.
func IsHashMismatch(err error) bool {
return errors.Is(err, ErrHashMismatch)
}
// CacheIndex is a list of files and their digests.
type CacheIndex struct {
Files []struct {
Name string `json:"name"`
Digest string `json:"digest"`
} `json:"files"`
}
// Find returns the digest of a file by name and a boolean indicating if the file was found.
func (c CacheIndex) Find(key string) (string, bool) {
for _, f := range c.Files {
if f.Name == key {
return f.Digest, true
}
}
return "", false
}
// Add adds an entry to the index.
//
// If the key already exists in the index and the value is the same, nothing will happen.
//
// If the key already exists in the index and the value is different, the key will be removed and re-added.
//
// If the key does not exist in the index, it will be added.
func (c *CacheIndex) Add(key, value string) {
if d, ok := c.Find(key); ok && d == value {
return
} else if ok {
c.Remove(key)
}
c.Files = append(c.Files, struct {
Name string `json:"name"`
Digest string `json:"digest"`
}{
Name: key,
Digest: value,
})
}
// Remove removes an entry from the index.
func (c *CacheIndex) Remove(key string) {
for i, f := range c.Files {
if f.Name == key {
c.Files = append(c.Files[:i], c.Files[i+1:]...)
return
}
}
}
// Store is a cache for storing and retrieving remote workflows.
type Store struct {
root string
index CacheIndex
sync sync.RWMutex
indexLock sync.Mutex
}
// NewStore creates a new store at the given path.
func NewStore(path string) (*Store, error) {
index := CacheIndex{}
indexPath := filepath.Join(path, "index.json")
if _, err := os.Stat(indexPath); os.IsNotExist(err) {
err := os.MkdirAll(path, 0755)
if err != nil {
return nil, err
}
_, err = os.Create(indexPath)
if err != nil {
return nil, err
}
if err := os.WriteFile(indexPath, []byte("{}"), 0644); err != nil {
return nil, err
}
} else if err != nil {
return nil, err
} else {
b, err := os.ReadFile(indexPath)
if err != nil {
return nil, err
}
if err := json.Unmarshal(b, &index); err != nil {
return nil, err
}
}
return &Store{
root: path,
index: index,
}, nil
}
// DefaultStore creates a new store in the default location:
//
// $VAI_CACHE || $HOME/.vai/cache
func DefaultStore() (*Store, error) {
if cache := os.Getenv(CacheEnvVar); cache != "" {
return NewStore(cache)
}
home, err := os.UserHomeDir()
if err != nil {
return nil, err
}
cache := filepath.Join(home, ".vai", "cache")
return NewStore(cache)
}
// Fetch retrieves a workflow from the store by key (SHA256).
func (s *Store) Fetch(key string) (Workflow, error) {
s.sync.RLock()
defer s.sync.RUnlock()
s.indexLock.Lock()
defer s.indexLock.Unlock()
sha, ok := s.index.Find(key)
if !ok {
return nil, fmt.Errorf("key not found")
}
path := filepath.Join(s.root, sha)
f, err := os.Open(path)
if err != nil {
return nil, err
}
defer f.Close()
hasher := sha256.New()
if _, err := io.Copy(hasher, f); err != nil {
return nil, err
}
if fmt.Sprintf("%x", hasher.Sum(nil)) != sha {
return nil, ErrHashMismatch
}
f.Close()
return ReadAndValidate(path)
}
// Store a workflow in the store.
func (s *Store) Store(key string, r io.Reader) error {
s.sync.Lock()
defer s.sync.Unlock()
s.indexLock.Lock()
defer s.indexLock.Unlock()
sha := sha256.New()
b, err := io.ReadAll(r)
if err != nil {
return err
}
if _, err := sha.Write(b); err != nil {
return err
}
hash := fmt.Sprintf("%x", sha.Sum(nil))
path := filepath.Join(s.root, hash)
if err := os.WriteFile(path, b, 0644); err != nil {
return err
}
s.index.Add(key, hash)
indexPath := filepath.Join(s.root, "index.json")
b, err = json.Marshal(s.index)
if err != nil {
return err
}
return os.WriteFile(indexPath, b, 0644)
}
// Delete a workflow from the store.
func (s *Store) Delete(key string) error {
s.sync.Lock()
defer s.sync.Unlock()
s.indexLock.Lock()
defer s.indexLock.Unlock()
sha, ok := s.index.Find(key)
if !ok {
return fmt.Errorf("key not found")
}
s.index.Remove(key)
indexPath := filepath.Join(s.root, "index.json")
b, err := json.Marshal(s.index)
if err != nil {
return err
}
if err := os.WriteFile(indexPath, b, 0644); err != nil {
return err
}
path := filepath.Join(s.root, sha)
return os.Remove(path)
}
// Exists checks if a workflow exists in the store.
func (s *Store) Exists(key string, r io.Reader) (bool, error) {
s.sync.RLock()
defer s.sync.RUnlock()
s.indexLock.Lock()
defer s.indexLock.Unlock()
sha, ok := s.index.Find(key)
if !ok {
return false, nil
}
path := filepath.Join(s.root, sha)
_, err := os.Stat(path)
if err != nil {
if os.IsNotExist(err) {
return false, nil
}
return false, err
}
hasher := sha256.New()
if _, err := io.Copy(hasher, r); err != nil {
return false, err
}
n := fmt.Sprintf("%x", hasher.Sum(nil))
logger.Debug("hashes", "new", n, "old", sha)
if n != sha {
return false, ErrHashMismatch
}
return true, nil
}