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