-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcache.go
More file actions
348 lines (285 loc) · 7.63 KB
/
cache.go
File metadata and controls
348 lines (285 loc) · 7.63 KB
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
// SPDX-License-Identifier: EUPL-1.2
// Package cache provides a storage-agnostic, JSON-based cache backed by any io.Medium.
package cache
import (
"encoding/json"
"io/fs"
"time"
"dappco.re/go/core"
coreio "dappco.re/go/core/io"
)
// DefaultTTL is the default cache expiry time.
//
// Usage example:
//
// c, err := cache.New(coreio.NewMockMedium(), "/tmp/cache", cache.DefaultTTL)
const DefaultTTL = 1 * time.Hour
// Cache stores JSON-encoded entries in a Medium-backed cache rooted at baseDir.
type Cache struct {
medium coreio.Medium
baseDir string
ttl time.Duration
}
// Entry is the serialized cache record written to the backing Medium.
type Entry struct {
Data json.RawMessage `json:"data"`
CachedAt time.Time `json:"cached_at"`
ExpiresAt time.Time `json:"expires_at"`
}
// New creates a cache and applies default Medium, base directory, and TTL values
// when callers pass zero values.
//
// c, err := cache.New(coreio.Local, "/tmp/cache", time.Hour)
func New(medium coreio.Medium, baseDir string, ttl time.Duration) (*Cache, error) {
if medium == nil {
medium = coreio.Local
}
if baseDir == "" {
cwd := currentDir()
if cwd == "" || cwd == "." {
return nil, core.E("cache.New", "failed to resolve current working directory", nil)
}
baseDir = normalizePath(core.JoinPath(cwd, ".core", "cache"))
} else {
baseDir = absolutePath(baseDir)
}
if ttl < 0 {
return nil, core.E("cache.New", "ttl must be >= 0", nil)
}
if ttl == 0 {
ttl = DefaultTTL
}
if err := medium.EnsureDir(baseDir); err != nil {
return nil, core.E("cache.New", "failed to create cache directory", err)
}
return &Cache{
medium: medium,
baseDir: baseDir,
ttl: ttl,
}, nil
}
// Path returns the storage path used for key and rejects path traversal
// attempts.
//
// path, err := c.Path("github/acme/repos")
func (c *Cache) Path(key string) (string, error) {
if err := c.ensureConfigured("cache.Path"); err != nil {
return "", err
}
baseDir := absolutePath(c.baseDir)
path := absolutePath(core.JoinPath(baseDir, key+".json"))
pathPrefix := normalizePath(core.Concat(baseDir, pathSeparator()))
if path != baseDir && !core.HasPrefix(path, pathPrefix) {
return "", core.E("cache.Path", "invalid cache key: path traversal attempt", nil)
}
return path, nil
}
// Get unmarshals the cached item into dest if it exists and has not expired.
//
// found, err := c.Get("github/acme/repos", &repos)
func (c *Cache) Get(key string, dest any) (bool, error) {
if err := c.ensureReady("cache.Get"); err != nil {
return false, err
}
path, err := c.Path(key)
if err != nil {
return false, err
}
dataStr, err := c.medium.Read(path)
if err != nil {
if core.Is(err, fs.ErrNotExist) {
return false, nil
}
return false, core.E("cache.Get", "failed to read cache file", err)
}
var entry Entry
entryResult := core.JSONUnmarshalString(dataStr, &entry)
if !entryResult.OK {
return false, nil
}
if time.Now().After(entry.ExpiresAt) {
return false, nil
}
if err := core.JSONUnmarshal(entry.Data, dest); !err.OK {
return false, core.E("cache.Get", "failed to unmarshal cached data", err.Value.(error))
}
return true, nil
}
// Set marshals data and stores it in the cache.
//
// err := c.Set("github/acme/repos", repos)
func (c *Cache) Set(key string, data any) error {
if err := c.ensureReady("cache.Set"); err != nil {
return err
}
path, err := c.Path(key)
if err != nil {
return err
}
if err := c.medium.EnsureDir(core.PathDir(path)); err != nil {
return core.E("cache.Set", "failed to create directory", err)
}
dataResult := core.JSONMarshal(data)
if !dataResult.OK {
return core.E("cache.Set", "failed to marshal cache data", dataResult.Value.(error))
}
ttl := c.ttl
if ttl < 0 {
return core.E("cache.Set", "cache ttl must be >= 0", nil)
}
if ttl == 0 {
ttl = DefaultTTL
}
entry := Entry{
Data: dataResult.Value.([]byte),
CachedAt: time.Now(),
ExpiresAt: time.Now().Add(ttl),
}
entryBytes, err := json.MarshalIndent(entry, "", " ")
if err != nil {
return core.E("cache.Set", "failed to marshal cache entry", err)
}
if err := c.medium.Write(path, string(entryBytes)); err != nil {
return core.E("cache.Set", "failed to write cache file", err)
}
return nil
}
// Delete removes the cached item for key.
//
// err := c.Delete("github/acme/repos")
func (c *Cache) Delete(key string) error {
if err := c.ensureReady("cache.Delete"); err != nil {
return err
}
path, err := c.Path(key)
if err != nil {
return err
}
err = c.medium.Delete(path)
if core.Is(err, fs.ErrNotExist) {
return nil
}
if err != nil {
return core.E("cache.Delete", "failed to delete cache file", err)
}
return nil
}
// DeleteMany removes several cached items in one call.
//
// err := c.DeleteMany("github/acme/repos", "github/acme/meta")
func (c *Cache) DeleteMany(keys ...string) error {
if err := c.ensureReady("cache.DeleteMany"); err != nil {
return err
}
for _, key := range keys {
path, err := c.Path(key)
if err != nil {
return err
}
err = c.medium.Delete(path)
if core.Is(err, fs.ErrNotExist) {
continue
}
if err != nil {
return core.E("cache.DeleteMany", "failed to delete cache file", err)
}
}
return nil
}
// Clear removes all cached items under the cache base directory.
//
// err := c.Clear()
func (c *Cache) Clear() error {
if err := c.ensureReady("cache.Clear"); err != nil {
return err
}
if err := c.medium.DeleteAll(c.baseDir); err != nil {
return core.E("cache.Clear", "failed to clear cache", err)
}
return nil
}
// Age reports how long ago key was cached, or -1 if it is missing or unreadable.
//
// age := c.Age("github/acme/repos")
func (c *Cache) Age(key string) time.Duration {
if err := c.ensureReady("cache.Age"); err != nil {
return -1
}
path, err := c.Path(key)
if err != nil {
return -1
}
dataStr, err := c.medium.Read(path)
if err != nil {
return -1
}
var entry Entry
entryResult := core.JSONUnmarshalString(dataStr, &entry)
if !entryResult.OK {
return -1
}
return time.Since(entry.CachedAt)
}
// GitHub-specific cache keys
// GitHubReposKey returns the cache key used for an organisation's repo list.
//
// key := cache.GitHubReposKey("acme")
func GitHubReposKey(org string) string {
return core.JoinPath("github", org, "repos")
}
// GitHubRepoKey returns the cache key used for a repository metadata entry.
//
// key := cache.GitHubRepoKey("acme", "widgets")
func GitHubRepoKey(org, repo string) string {
return core.JoinPath("github", org, repo, "meta")
}
func pathSeparator() string {
if ds := core.Env("DS"); ds != "" {
return ds
}
return "/"
}
func normalizePath(path string) string {
ds := pathSeparator()
normalized := core.Replace(path, "\\", ds)
if ds != "/" {
normalized = core.Replace(normalized, "/", ds)
}
return core.CleanPath(normalized, ds)
}
func absolutePath(path string) string {
normalized := normalizePath(path)
if core.PathIsAbs(normalized) {
return normalized
}
cwd := currentDir()
if cwd == "" || cwd == "." {
return normalized
}
return normalizePath(core.JoinPath(cwd, normalized))
}
func currentDir() string {
cwd := normalizePath(core.Env("PWD"))
if cwd != "" && cwd != "." {
return cwd
}
return normalizePath(core.Env("DIR_CWD"))
}
func (c *Cache) ensureConfigured(op string) error {
if c == nil {
return core.E(op, "cache is nil", nil)
}
if c.baseDir == "" {
return core.E(op, "cache base directory is empty; construct with cache.New", nil)
}
return nil
}
func (c *Cache) ensureReady(op string) error {
if err := c.ensureConfigured(op); err != nil {
return err
}
if c.medium == nil {
return core.E(op, "cache medium is nil; construct with cache.New", nil)
}
return nil
}