-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathcache.go
116 lines (90 loc) · 2.48 KB
/
cache.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
package main
import (
"errors"
"io"
"log/slog"
"os"
"path/filepath"
"time"
)
var errCacheExpired = errors.New("cached value expired")
type Cache interface {
Set(ct Type, key string, value io.Reader) error
Get(ct Type, key string, receiver io.Writer) error
}
type NopCache struct{}
func (c *NopCache) Set(_ Type, _ string, _ io.Reader) error {
return nil
}
func (c *NopCache) Get(_ Type, _ string, _ io.Writer) error {
return nil
}
type FsCache struct {
rootPath string
maxAge time.Duration
logger *slog.Logger
}
type Type int
const (
TypeLists Type = iota
)
// NewCache creates a new local storage backed cache for avatars and player lists.
func NewCache(rootDir string, maxAge time.Duration) (FsCache, error) {
cache := FsCache{rootPath: rootDir, maxAge: maxAge, logger: slog.Default().WithGroup("cache")}
if errInit := cache.init(); errInit != nil {
return FsCache{}, errInit
}
return cache, nil
}
// init creates the directory structure used to store locally cached files.
func (cache FsCache) init() error {
for _, p := range []Type{TypeLists} {
if errMkDir := os.MkdirAll(cache.getPath(p, ""), 0o770); errMkDir != nil {
return errors.Join(errMkDir, errCacheSetup)
}
}
return nil
}
func (cache FsCache) getPath(cacheType Type, key string) string {
switch cacheType {
case TypeLists:
return filepath.Join(cache.rootPath, "lists", key)
default:
cache.logger.Error("Got unknown cache type", slog.Int("type", int(cacheType)))
return ""
}
}
func (cache FsCache) Set(ct Type, key string, value io.Reader) error {
fullPath := cache.getPath(ct, key)
if errMkdir := os.MkdirAll(filepath.Dir(fullPath), os.ModePerm); errMkdir != nil {
return errors.Join(errMkdir, errCreateCacheDir)
}
openFile, errOf := os.OpenFile(fullPath, os.O_WRONLY|os.O_CREATE, 0o660)
if errOf != nil {
return errors.Join(errOf, errOpenCacheFile)
}
defer LogClose(openFile)
if _, errWrite := io.Copy(openFile, value); errWrite != nil {
return errors.Join(errWrite, errWriteCacheFile)
}
return nil
}
func (cache FsCache) Get(ct Type, key string, receiver io.Writer) error {
openFile, errOf := os.Open(cache.getPath(ct, key))
if errOf != nil {
return errCacheExpired
}
defer LogClose(openFile)
stat, errStat := openFile.Stat()
if errStat != nil {
return errCacheExpired
}
if time.Since(stat.ModTime()) > cache.maxAge {
return errCacheExpired
}
_, errCopy := io.Copy(receiver, openFile)
if errCopy != nil {
return errors.Join(errCopy, errReadCacheFile)
}
return nil
}