]> git.lizzy.rs Git - go-anidb.git/blob - cachetemplate.go
anime: Make cached Anime expire earlier if they're Incomplete
[go-anidb.git] / cachetemplate.go
1 // +build never
2
3 package anidb
4
5 // Copy&paste this for new cache types
6 // globally replace: Strut strut SID sid
7
8 import (
9         "sync"
10         "time"
11 )
12
13 type Strut struct {
14         Cached time.Time
15 }
16
17 func (v *Strut) touch() {
18         v.Cached = time.Now()
19 }
20 func (v *Strut) isStale(d time.Duration) bool {
21         return time.Now().Sub(v.Cached) > d
22 }
23
24 type SID int
25
26 func (sid SID) Strut() *Strut {
27         return strutCache.Get(sid)
28 }
29
30 var StrutCacheDuration = DefaultCacheDuration
31
32 var strutCache = strutCacheStruct{baseCache: newBaseCache()}
33
34 type strutCacheStruct struct{ baseCache }
35
36 func (c *strutCacheStruct) Get(id SID) *Strut {
37         return c.baseCache.Get(int(id)).(*Strut)
38 }
39
40 func (c *strutCacheStruct) Set(id SID, v *Strut) {
41         c.baseCache.Set(int(id), v)
42 }
43
44 func (c *strutCacheStruct) Intent(id SID, ch chan *Strut) (ok bool) {
45         ch2 := make(chan cacheable, 1)
46         go func() { ch <- (<-ch2).(*Strut) }()
47         return c.baseCache.Intent(int(id), ch2)
48 }
49
50 func (adb *AniDB) StrutBySID(id SID) <-chan *Strut {
51         ch := make(chan *Strut, 1)
52         if v := id.Strut(); !v.isStale(StrutCacheDuration) {
53                 ch <- v
54                 close(ch)
55                 return ch
56         }
57
58         if strutCache.Intent(id, ch) {
59                 return ch
60         }
61
62         go func() {
63                 var v *Strut
64                 strutCache.Set(id, v)
65         }()
66         return ch
67 }