]> git.lizzy.rs Git - go-anidb.git/blob - cache.go
64cae67f451d6f4845af248635d2b5349befd67c
[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         if flock := lockFile(cachePath(keys...)); flock != nil {
149                 flock.Lock()
150                 defer flock.Unlock()
151         }
152
153         fh, err := c.Open(keys...)
154         if err != nil {
155                 return err
156         }
157         defer func() {
158                 if e := fh.Close(); err == nil {
159                         err = e
160                 }
161         }()
162
163         val := reflect.ValueOf(v)
164         if k := val.Kind(); k == reflect.Ptr || k == reflect.Interface {
165                 val = val.Elem()
166         }
167         if !val.CanSet() {
168                 // panic because this is an internal coding mistake
169                 panic("(*cacheDir).Get(): given Cacheable is not setable")
170         }
171         gz, err := gzip.NewReader(fh)
172         if err != nil {
173                 return err
174         }
175         defer func() {
176                 if e := gz.Close(); err == nil {
177                         err = e
178                 }
179         }()
180
181         // defer func() {
182         //      if err == io.EOF {
183         //              err = nil
184         //      }
185         // }()
186
187         switch f := gz.Header.Comment; f {
188         case "encoding/gob":
189                 dec := gob.NewDecoder(gz)
190                 err = dec.Decode(v)
191         default:
192                 return errors.New(fmt.Sprintf("Cached data (format %q) is not in a known format", f))
193         }
194
195         return
196 }
197
198 func (c *cacheDir) Set(v Cacheable, keys ...cacheKey) (n int64, err error) {
199         if v := reflect.ValueOf(v); !v.IsValid() {
200                 panic("reflect.ValueOf() returned invaled value")
201         } else if k := v.Kind(); k == reflect.Ptr || k == reflect.Interface {
202                 if v.IsNil() {
203                         return // no point in saving nil
204                 }
205         }
206         defer func() {
207                 log.Println("Set entry", keys, "(error", err, ")")
208         }()
209
210         // First we encode to memory -- we don't want to create/truncate a file and put bad data in it.
211         buf := bytes.Buffer{}
212         gz, err := gzip.NewWriterLevel(&buf, gzip.BestCompression)
213         if err != nil {
214                 return 0, err
215         }
216         gz.Header.Comment = "encoding/gob"
217
218         // it doesn't matter if the caller doesn't see this,
219         // the important part is that the cache does.
220         v.Touch()
221
222         enc := gob.NewEncoder(gz)
223         err = enc.Encode(v)
224
225         if e := gz.Close(); err == nil {
226                 err = e
227         }
228
229         if err != nil {
230                 return 0, err
231         }
232
233         // We have good data, time to actually put it in the cache
234         if flock := lockFile(cachePath(keys...)); flock != nil {
235                 flock.Lock()
236                 defer flock.Unlock()
237         }
238
239         fh, err := c.Create(keys...)
240         if err != nil {
241                 return 0, err
242         }
243         defer func() {
244                 if e := fh.Close(); err == nil {
245                         err = e
246                 }
247         }()
248         n, err = io.Copy(fh, &buf)
249         return
250 }
251
252 // Checks if the given keys are not marked as invalid.
253 //
254 // If the key was marked as invalid but is no longer considered
255 // so, deletes the invalid marker.
256 func (c *cacheDir) CheckValid(keys ...cacheKey) bool {
257         invKeys := append([]cacheKey{"invalid"}, keys...)
258         inv := invalidKeyCache{}
259
260         if cache.Get(&inv, invKeys...) == nil {
261                 if inv.IsStale() {
262                         cache.Delete(invKeys...)
263                 } else {
264                         return false
265                 }
266         }
267         return true
268 }
269
270 // Deletes the given keys and marks them as invalid.
271 //
272 // They are considered invalid for InvalidKeyCacheDuration.
273 func (c *cacheDir) MarkInvalid(keys ...cacheKey) error {
274         invKeys := append([]cacheKey{"invalid"}, keys...)
275
276         cache.Delete(keys...)
277         _, err := cache.Set(&invalidKeyCache{}, invKeys...)
278         return err
279 }