]> git.lizzy.rs Git - go-anidb.git/blob - cache.go
anidb: Implement GroupByName
[go-anidb.git] / cache.go
1 package anidb
2
3 import (
4         "bytes"
5         "compress/gzip"
6         "encoding/gob"
7         "errors"
8         "fmt"
9         "io"
10         "log"
11         "os"
12         "path"
13         "reflect"
14         "regexp"
15         "sync"
16         "time"
17 )
18
19 var _ log.Logger
20
21 type Cacheable interface {
22         // Updates the last modified time
23         Touch()
24         // Returns true if the Cacheable is nil, or if the last modified time is too old.
25         IsStale() bool
26 }
27
28 func init() {
29         gob.RegisterName("*github.com/Kovensky/go-anidb.invalidKeyCache", &invalidKeyCache{})
30 }
31
32 type invalidKeyCache struct{ time.Time }
33
34 func (c *invalidKeyCache) Touch() {
35         c.Time = time.Now()
36 }
37 func (c *invalidKeyCache) IsStale() bool {
38         return time.Now().Sub(c.Time) > InvalidKeyCacheDuration
39 }
40
41 type cacheDir struct {
42         *sync.RWMutex
43
44         CacheDir string
45 }
46
47 func init() {
48         if err := SetCacheDir(path.Join(os.TempDir(), "anidb", "cache")); err != nil {
49                 panic(err)
50         }
51 }
52
53 var cache cacheDir
54
55 // Sets the cache directory to the given path.
56 //
57 // go-anidb needs a valid cache directory to function, so, during module
58 // initialization, it uses os.TempDir() to set a default cache dir.
59 // go-anidb panics if it's unable to set the default cache dir.
60 func SetCacheDir(path string) (err error) {
61         m := cache.RWMutex
62         if m == nil {
63                 m = &sync.RWMutex{}
64                 cache.RWMutex = m
65         }
66         cache.Lock()
67
68         if err = os.MkdirAll(path, 0755|os.ModeDir); err != nil {
69                 cache.Unlock()
70                 return err
71         }
72
73         cache = cacheDir{
74                 RWMutex:  m,
75                 CacheDir: path,
76         }
77
78         cache.Unlock()
79         RefreshTitles()
80         return nil
81 }
82
83 // Returns the current cache dir.
84 func GetCacheDir() (path string) {
85         cache.RLock()
86         defer cache.RUnlock()
87
88         return cache.CacheDir
89 }
90
91 type cacheKey interface{}
92
93 // All "bad characters" that can't go in Windows paths.
94 // It's a superset of the "bad characters" on other OSes, so this works.
95 var badPath = regexp.MustCompile(`[\\/:\*\?\"<>\|]`)
96
97 func stringify(stuff ...cacheKey) []string {
98         ret := make([]string, len(stuff))
99         for i := range stuff {
100                 s := fmt.Sprint(stuff[i])
101                 ret[i] = badPath.ReplaceAllLiteralString(s, "_")
102         }
103         return ret
104 }
105
106 // Each key but the last is treated as a directory.
107 // The last key is treated as a regular file.
108 //
109 // This also means that cache keys that are file-backed
110 // cannot have subkeys.
111 func cachePath(keys ...cacheKey) string {
112         parts := append([]string{GetCacheDir()}, stringify(keys...)...)
113         p := path.Join(parts...)
114         return p
115 }
116
117 // Opens the file that backs the specified keys.
118 func (c *cacheDir) Open(keys ...cacheKey) (fh *os.File, err error) {
119         subItem := cachePath(keys...)
120         return os.Open(subItem)
121 }
122
123 // Creates a new file to back the specified keys.
124 func (c *cacheDir) Create(keys ...cacheKey) (fh *os.File, err error) {
125         subItem := cachePath(keys...)
126         subDir := path.Dir(subItem)
127
128         if err = os.MkdirAll(subDir, 0755|os.ModeDir); err != nil {
129                 return nil, err
130         }
131         return os.Create(subItem)
132 }
133
134 // Deletes the file that backs the specified keys.
135 func (c *cacheDir) Delete(keys ...cacheKey) (err error) {
136         return os.Remove(cachePath(keys...))
137 }
138
139 // Deletes the specified key and all subkeys.
140 func (c *cacheDir) DeleteAll(keys ...cacheKey) (err error) {
141         return os.RemoveAll(cachePath(keys...))
142 }
143
144 func (c *cacheDir) Get(v Cacheable, keys ...cacheKey) (err error) {
145         defer func() {
146                 log.Println("Got entry", keys, "(error", err, ")")
147         }()
148
149         val := reflect.ValueOf(v)
150         if k := val.Kind(); k == reflect.Ptr || k == reflect.Interface {
151                 val = val.Elem()
152         }
153         if !val.CanSet() {
154                 // panic because this is an internal coding mistake
155                 panic("(*cacheDir).Get(): given Cacheable is not setable")
156         }
157
158         flock := lockFile(cachePath(keys...))
159         if flock != nil {
160                 flock.Lock()
161         }
162         defer func() {
163                 if flock != nil {
164                         flock.Unlock()
165                 }
166         }()
167
168         fh, err := c.Open(keys...)
169         if err != nil {
170                 return err
171         }
172
173         buf := bytes.Buffer{}
174         if _, err = io.Copy(&buf, fh); err != nil {
175                 fh.Close()
176                 return err
177         }
178         if err = fh.Close(); err != nil {
179                 return err
180         }
181
182         if flock != nil {
183                 flock.Unlock()
184                 flock = nil
185         }
186
187         gz, err := gzip.NewReader(&buf)
188         if err != nil {
189                 return err
190         }
191         defer func() {
192                 if e := gz.Close(); err == nil {
193                         err = e
194                 }
195         }()
196
197         switch f := gz.Header.Comment; f {
198         case "encoding/gob":
199                 dec := gob.NewDecoder(gz)
200                 err = dec.Decode(v)
201         default:
202                 return errors.New(fmt.Sprintf("Cached data (format %q) is not in a known format", f))
203         }
204
205         return
206 }
207
208 func (c *cacheDir) Set(v Cacheable, keys ...cacheKey) (n int64, err error) {
209         if v := reflect.ValueOf(v); !v.IsValid() {
210                 panic("reflect.ValueOf() returned invaled value")
211         } else if k := v.Kind(); k == reflect.Ptr || k == reflect.Interface {
212                 if v.IsNil() {
213                         return // no point in saving nil
214                 }
215         }
216         defer func() {
217                 log.Println("Set entry", keys, "(error", err, ")")
218         }()
219
220         // First we encode to memory -- we don't want to create/truncate a file and put bad data in it.
221         buf := bytes.Buffer{}
222         gz, err := gzip.NewWriterLevel(&buf, gzip.BestCompression)
223         if err != nil {
224                 return 0, err
225         }
226         gz.Header.Comment = "encoding/gob"
227
228         // it doesn't matter if the caller doesn't see this,
229         // the important part is that the cache does.
230         v.Touch()
231
232         enc := gob.NewEncoder(gz)
233         err = enc.Encode(v)
234
235         if e := gz.Close(); err == nil {
236                 err = e
237         }
238
239         if err != nil {
240                 return 0, err
241         }
242
243         // We have good data, time to actually put it in the cache
244         if flock := lockFile(cachePath(keys...)); flock != nil {
245                 flock.Lock()
246                 defer flock.Unlock()
247         }
248
249         fh, err := c.Create(keys...)
250         if err != nil {
251                 return 0, err
252         }
253         defer func() {
254                 if e := fh.Close(); err == nil {
255                         err = e
256                 }
257         }()
258         n, err = io.Copy(fh, &buf)
259         return
260 }
261
262 // Checks if the given keys are not marked as invalid.
263 //
264 // If the key was marked as invalid but is no longer considered
265 // so, deletes the invalid marker.
266 func (c *cacheDir) CheckValid(keys ...cacheKey) bool {
267         invKeys := append([]cacheKey{"invalid"}, keys...)
268         inv := invalidKeyCache{}
269
270         if cache.Get(&inv, invKeys...) == nil {
271                 if inv.IsStale() {
272                         cache.Delete(invKeys...)
273                 } else {
274                         return false
275                 }
276         }
277         return true
278 }
279
280 // Deletes the given keys and marks them as invalid.
281 //
282 // They are considered invalid for InvalidKeyCacheDuration.
283 func (c *cacheDir) MarkInvalid(keys ...cacheKey) error {
284         invKeys := append([]cacheKey{"invalid"}, keys...)
285
286         cache.Delete(keys...)
287         _, err := cache.Set(&invalidKeyCache{}, invKeys...)
288         return err
289 }