18 type Cacheable interface {
19 // Updates the last modified time
21 // Returns true if the Cacheable is nil, or if the last modified time is too old.
26 gob.RegisterName("*github.com/Kovensky/go-anidb.invalidKeyCache", &invalidKeyCache{})
29 type invalidKeyCache struct{ time.Time }
31 func (c *invalidKeyCache) Touch() {
34 func (c *invalidKeyCache) IsStale() bool {
35 return time.Now().Sub(c.Time) > InvalidKeyCacheDuration
38 type cacheDir struct {
45 if err := SetCacheDir(path.Join(os.TempDir(), "anidb", "cache")); err != nil {
52 // Sets the cache directory to the given path.
54 // go-anidb needs a valid cache directory to function, so, during module
55 // initialization, it uses os.TempDir() to set a default cache dir.
56 // go-anidb panics if it's unable to set the default cache dir.
57 func SetCacheDir(path string) (err error) {
65 if err = os.MkdirAll(path, 0755|os.ModeDir); err != nil {
80 // Returns the current cache dir.
81 func GetCacheDir() (path string) {
88 type cacheKey interface{}
90 // All "bad characters" that can't go in Windows paths.
91 // It's a superset of the "bad characters" on other OSes, so this works.
92 var badPath = regexp.MustCompile(`[\\/:\*\?\"<>\|]`)
94 func stringify(stuff ...cacheKey) []string {
95 ret := make([]string, len(stuff))
96 for i := range stuff {
97 s := fmt.Sprint(stuff[i])
98 ret[i] = badPath.ReplaceAllLiteralString(s, "_")
103 // Each key but the last is treated as a directory.
104 // The last key is treated as a regular file.
106 // This also means that cache keys that are file-backed
107 // cannot have subkeys.
108 func cachePath(keys ...cacheKey) string {
109 parts := append([]string{GetCacheDir()}, stringify(keys...)...)
110 p := path.Join(parts...)
114 // Opens the file that backs the specified keys.
115 func (c *cacheDir) Open(keys ...cacheKey) (fh *os.File, err error) {
116 subItem := cachePath(keys...)
117 return os.Open(subItem)
120 // Creates a new file to back the specified keys.
121 func (c *cacheDir) Create(keys ...cacheKey) (fh *os.File, err error) {
122 subItem := cachePath(keys...)
123 subDir := path.Dir(subItem)
125 if err = os.MkdirAll(subDir, 0755|os.ModeDir); err != nil {
128 return os.Create(subItem)
131 // Deletes the file that backs the specified keys.
132 func (c *cacheDir) Delete(keys ...cacheKey) (err error) {
133 return os.Remove(cachePath(keys...))
136 // Deletes the specified key and all subkeys.
137 func (c *cacheDir) DeleteAll(keys ...cacheKey) (err error) {
138 return os.RemoveAll(cachePath(keys...))
141 func (c *cacheDir) Get(v Cacheable, keys ...cacheKey) (err error) {
143 val := reflect.ValueOf(v)
144 if k := val.Kind(); k == reflect.Ptr || k == reflect.Interface {
148 // panic because this is an internal coding mistake
149 panic("(*cacheDir).Get(): given Cacheable is not setable")
152 flock := lockFile(cachePath(keys...))
162 fh, err := c.Open(keys...)
167 buf := bytes.Buffer{}
168 if _, err = io.Copy(&buf, fh); err != nil {
172 if err = fh.Close(); err != nil {
181 gz, err := gzip.NewReader(&buf)
186 if e := gz.Close(); err == nil {
191 switch f := gz.Header.Comment; f {
193 dec := gob.NewDecoder(gz)
196 return errors.New(fmt.Sprintf("Cached data (format %q) is not in a known format", f))
202 func (c *cacheDir) Set(v Cacheable, keys ...cacheKey) (n int64, err error) {
203 if v := reflect.ValueOf(v); !v.IsValid() {
204 panic("reflect.ValueOf() returned invaled value")
205 } else if k := v.Kind(); k == reflect.Ptr || k == reflect.Interface {
207 return // no point in saving nil
211 // First we encode to memory -- we don't want to create/truncate a file and put bad data in it.
212 buf := bytes.Buffer{}
213 gz, err := gzip.NewWriterLevel(&buf, gzip.BestCompression)
217 gz.Header.Comment = "encoding/gob"
219 // it doesn't matter if the caller doesn't see this,
220 // the important part is that the cache does.
223 enc := gob.NewEncoder(gz)
226 if e := gz.Close(); err == nil {
234 // We have good data, time to actually put it in the cache
235 if flock := lockFile(cachePath(keys...)); flock != nil {
240 fh, err := c.Create(keys...)
245 if e := fh.Close(); err == nil {
249 n, err = io.Copy(fh, &buf)
253 // Checks if the given keys are not marked as invalid.
255 // If the key was marked as invalid but is no longer considered
256 // so, deletes the invalid marker.
257 func (c *cacheDir) CheckValid(keys ...cacheKey) bool {
258 invKeys := append([]cacheKey{"invalid"}, keys...)
259 inv := invalidKeyCache{}
261 if cache.Get(&inv, invKeys...) == nil {
263 cache.Delete(invKeys...)
271 // Deletes the given keys and marks them as invalid.
273 // They are considered invalid for InvalidKeyCacheDuration.
274 func (c *cacheDir) MarkInvalid(keys ...cacheKey) error {
275 invKeys := append([]cacheKey{"invalid"}, keys...)
277 cache.Delete(keys...)
278 _, err := cache.Set(&invalidKeyCache{}, invKeys...)