21 type Cacheable interface {
22 // Updates the last modified time
24 // Returns true if the Cacheable is nil, or if the last modified time is too old.
29 gob.RegisterName("*github.com/Kovensky/go-anidb.invalidKeyCache", &invalidKeyCache{})
32 type invalidKeyCache struct{ time.Time }
34 func (c *invalidKeyCache) Touch() {
37 func (c *invalidKeyCache) IsStale() bool {
38 return time.Now().Sub(c.Time) > InvalidKeyCacheDuration
41 type cacheDir struct {
48 if err := SetCacheDir(path.Join(os.TempDir(), "anidb", "cache")); err != nil {
55 func SetCacheDir(path string) (err error) {
63 if err = os.MkdirAll(path, 0755|os.ModeDir); err != nil {
78 func GetCacheDir() (path string) {
85 type cacheKey interface{}
87 // All "bad characters" that can't go in Windows paths.
88 // It's a superset of the "bad characters" on other OSes, so this works.
89 var badPath = regexp.MustCompile(`[\\/:\*\?\"<>\|]`)
91 func stringify(stuff ...cacheKey) []string {
92 ret := make([]string, len(stuff))
93 for i := range stuff {
94 s := fmt.Sprint(stuff[i])
95 ret[i] = badPath.ReplaceAllLiteralString(s, "_")
100 // Each key but the last is treated as a directory.
101 // The last key is treated as a regular file.
103 // This also means that cache keys that are file-backed
104 // cannot have subkeys.
105 func cachePath(keys ...cacheKey) string {
106 parts := append([]string{GetCacheDir()}, stringify(keys...)...)
107 p := path.Join(parts...)
111 // Opens the file that backs the specified keys.
112 func (c *cacheDir) Open(keys ...cacheKey) (fh *os.File, err error) {
113 subItem := cachePath(keys...)
114 return os.Open(subItem)
117 // Creates a new file to back the specified keys.
118 func (c *cacheDir) Create(keys ...cacheKey) (fh *os.File, err error) {
119 subItem := cachePath(keys...)
120 subDir := path.Dir(subItem)
122 if err = os.MkdirAll(subDir, 0755|os.ModeDir); err != nil {
125 return os.Create(subItem)
128 // Deletes the file that backs the specified keys.
129 func (c *cacheDir) Delete(keys ...cacheKey) (err error) {
130 return os.Remove(cachePath(keys...))
133 // Deletes the specified key and all subkeys.
134 func (c *cacheDir) DeleteAll(keys ...cacheKey) (err error) {
135 return os.RemoveAll(cachePath(keys...))
138 func (c *cacheDir) Get(v Cacheable, keys ...cacheKey) (err error) {
140 log.Println("Got entry", keys, "(error", err, ")")
142 flock := lockFile(cachePath(keys...))
146 fh, err := c.Open(keys...)
151 if e := fh.Close(); err == nil {
156 val := reflect.ValueOf(v)
157 if k := val.Kind(); k == reflect.Ptr || k == reflect.Interface {
161 // panic because this is an internal coding mistake
162 panic("(*cacheDir).Get(): given Cacheable is not setable")
164 gz, err := gzip.NewReader(fh)
169 if e := gz.Close(); err == nil {
175 // if err == io.EOF {
180 switch f := gz.Header.Comment; f {
182 dec := gob.NewDecoder(gz)
185 return errors.New(fmt.Sprintf("Cached data (format %q) is not in a known format", f))
191 func (c *cacheDir) Set(v Cacheable, keys ...cacheKey) (n int64, err error) {
192 if v := reflect.ValueOf(v); !v.IsValid() {
193 panic("reflect.ValueOf() returned invaled value")
194 } else if k := v.Kind(); k == reflect.Ptr || k == reflect.Interface {
196 return // no point in saving nil
200 log.Println("Set entry", keys, "(error", err, ")")
203 // First we encode to memory -- we don't want to create/truncate a file and put bad data in it.
204 buf := bytes.Buffer{}
205 gz, err := gzip.NewWriterLevel(&buf, gzip.BestCompression)
209 gz.Header.Comment = "encoding/gob"
211 // it doesn't matter if the caller doesn't see this,
212 // the important part is that the cache does.
215 enc := gob.NewEncoder(gz)
218 if e := gz.Close(); err == nil {
226 // We have good data, time to actually put it in the cache
227 flock := lockFile(cachePath(keys...))
231 fh, err := c.Create(keys...)
236 if e := fh.Close(); err == nil {
240 n, err = io.Copy(fh, &buf)
244 // Checks if the given keys are not marked as invalid.
246 // If the key was marked as invalid but is no longer considered
247 // so, deletes the invalid marker.
248 func (c *cacheDir) CheckValid(keys ...cacheKey) bool {
249 invKeys := append([]cacheKey{"invalid"}, keys...)
250 inv := invalidKeyCache{}
252 if cache.Get(&inv, invKeys...) == nil {
254 cache.Delete(invKeys...)
262 // Deletes the given keys and marks them as invalid.
264 // They are considered invalid for InvalidKeyCacheDuration.
265 func (c *cacheDir) MarkInvalid(keys ...cacheKey) error {
266 invKeys := append([]cacheKey{"invalid"}, keys...)
268 cache.Delete(keys...)
269 _, err := cache.Set(&invalidKeyCache{}, invKeys...)