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 SetCacheDir(path.Join(os.TempDir(), "anidb", "cache"))
53 func SetCacheDir(path string) (err error) {
61 if err = os.MkdirAll(path, 0755|os.ModeDir); err != nil {
76 func GetCacheDir() (path string) {
83 type cacheKey interface{}
85 // All "bad characters" that can't go in Windows paths.
86 // It's a superset of the "bad characters" on other OSes, so this works.
87 var badPath = regexp.MustCompile(`[\\/:\*\?\"<>\|]`)
89 func stringify(stuff ...cacheKey) []string {
90 ret := make([]string, len(stuff))
91 for i := range stuff {
92 s := fmt.Sprint(stuff[i])
93 ret[i] = badPath.ReplaceAllLiteralString(s, "_")
98 // Each key but the last is treated as a directory.
99 // The last key is treated as a regular file.
101 // This also means that cache keys that are file-backed
102 // cannot have subkeys.
103 func cachePath(keys ...cacheKey) string {
104 parts := append([]string{GetCacheDir()}, stringify(keys...)...)
105 p := path.Join(parts...)
109 // Opens the file that backs the specified keys.
110 func (c *cacheDir) Open(keys ...cacheKey) (fh *os.File, err error) {
111 subItem := cachePath(keys...)
112 return os.Open(subItem)
115 // Creates a new file to back the specified keys.
116 func (c *cacheDir) Create(keys ...cacheKey) (fh *os.File, err error) {
117 subItem := cachePath(keys...)
118 subDir := path.Dir(subItem)
120 if err = os.MkdirAll(subDir, 0755|os.ModeDir); err != nil {
123 return os.Create(subItem)
126 // Deletes the file that backs the specified keys.
127 func (c *cacheDir) Delete(keys ...cacheKey) (err error) {
128 return os.Remove(cachePath(keys...))
131 // Deletes the specified key and all subkeys.
132 func (c *cacheDir) DeleteAll(keys ...cacheKey) (err error) {
133 return os.RemoveAll(cachePath(keys...))
136 func (c *cacheDir) Get(v Cacheable, keys ...cacheKey) (err error) {
138 log.Println("Got entry", keys, "(error", err, ")")
140 flock := lockFile(cachePath(keys...))
144 fh, err := c.Open(keys...)
149 if e := fh.Close(); err == nil {
154 val := reflect.ValueOf(v)
155 if k := val.Kind(); k == reflect.Ptr || k == reflect.Interface {
159 // panic because this is an internal coding mistake
160 panic("(*cacheDir).Get(): given Cacheable is not setable")
162 gz, err := gzip.NewReader(fh)
167 if e := gz.Close(); err == nil {
173 // if err == io.EOF {
178 switch f := gz.Header.Comment; f {
180 dec := gob.NewDecoder(gz)
183 return errors.New(fmt.Sprintf("Cached data (format %q) is not in a known format", f))
189 func (c *cacheDir) Set(v Cacheable, keys ...cacheKey) (n int64, err error) {
190 if v := reflect.ValueOf(v); !v.IsValid() {
191 panic("reflect.ValueOf() returned invaled value")
192 } else if k := v.Kind(); k == reflect.Ptr || k == reflect.Interface {
194 return // no point in saving nil
198 log.Println("Set entry", keys, "(error", err, ")")
201 // First we encode to memory -- we don't want to create/truncate a file and put bad data in it.
202 buf := bytes.Buffer{}
203 gz, err := gzip.NewWriterLevel(&buf, gzip.BestCompression)
207 gz.Header.Comment = "encoding/gob"
209 // it doesn't matter if the caller doesn't see this,
210 // the important part is that the cache does.
213 enc := gob.NewEncoder(gz)
216 if e := gz.Close(); err == nil {
224 // We have good data, time to actually put it in the cache
225 flock := lockFile(cachePath(keys...))
229 fh, err := c.Create(keys...)
234 if e := fh.Close(); err == nil {
238 n, err = io.Copy(fh, &buf)
242 // Checks if the given keys are not marked as invalid.
244 // If the key was marked as invalid but is no longer considered
245 // so, deletes the invalid marker.
246 func (c *cacheDir) CheckValid(keys ...cacheKey) bool {
247 invKeys := append([]cacheKey{"invalid"}, keys...)
248 inv := invalidKeyCache{}
250 if cache.Get(&inv, invKeys...) == nil {
252 cache.Delete(invKeys...)
260 // Deletes the given keys and marks them as invalid.
262 // They are considered invalid for InvalidKeyCacheDuration.
263 func (c *cacheDir) MarkInvalid(keys ...cacheKey) error {
264 invKeys := append([]cacheKey{"invalid"}, keys...)
266 cache.Delete(keys...)
267 _, err := cache.Set(&invalidKeyCache{}, invKeys...)