-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcache_file.go
More file actions
86 lines (69 loc) · 2.01 KB
/
cache_file.go
File metadata and controls
86 lines (69 loc) · 2.01 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
// Copyright 2017-2026 Allow2 Pty Ltd. All rights reserved.
// Use of this source code is governed by the Allow2 API and SDK Licence.
package allow2service
import (
"encoding/json"
"os"
"path/filepath"
"regexp"
"time"
)
// FileCache is a file-based permission cache.
// Each cache entry is stored as a separate JSON file in the cache directory.
type FileCache struct {
cacheDir string
}
// fileCacheEntry represents a cached value with expiry.
type fileCacheEntry struct {
Value string `json:"value"`
ExpiresAt int64 `json:"expiresAt"`
}
// NewFileCache creates a new FileCache with the given directory.
// The directory is created if it does not exist.
func NewFileCache(cacheDir string) *FileCache {
_ = os.MkdirAll(cacheDir, 0700)
return &FileCache{cacheDir: cacheDir}
}
// Get retrieves a cached value by key.
func (c *FileCache) Get(key string) (string, bool) {
path := c.keyToPath(key)
contents, err := os.ReadFile(path)
if err != nil {
return "", false
}
var entry fileCacheEntry
if err := json.Unmarshal(contents, &entry); err != nil {
_ = os.Remove(path)
return "", false
}
if time.Now().Unix() >= entry.ExpiresAt {
_ = os.Remove(path)
return "", false
}
return entry.Value, true
}
// Set stores a value in cache with the given TTL in seconds.
func (c *FileCache) Set(key, value string, ttlSeconds int) {
path := c.keyToPath(key)
entry := fileCacheEntry{
Value: value,
ExpiresAt: time.Now().Unix() + int64(ttlSeconds),
}
data, err := json.Marshal(entry)
if err != nil {
return
}
_ = os.WriteFile(path, data, 0600)
}
// Delete removes a cached value.
func (c *FileCache) Delete(key string) {
path := c.keyToPath(key)
_ = os.Remove(path)
}
// safeKeyRegex matches characters that are NOT safe for filenames.
var safeKeyRegex = regexp.MustCompile(`[^a-zA-Z0-9_\-]`)
// keyToPath converts a cache key to a safe filesystem path.
func (c *FileCache) keyToPath(key string) string {
safeKey := safeKeyRegex.ReplaceAllString(key, "_")
return filepath.Join(c.cacheDir, safeKey+".json")
}