forked from k5342/ikabot3
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcache.go
101 lines (88 loc) · 2.05 KB
/
cache.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
package main
import (
"encoding/json"
"fmt"
"io"
"os"
"path"
"path/filepath"
"sync"
"time"
)
type FileCacheBody struct {
Updated time.Time
Body *AllScheduleInfo
}
type FileCache struct {
sync.RWMutex
WorkDir string
FileCacheBody *FileCacheBody
CacheFileName string
}
func tryRestoreCache(workdir string, cacheFilename string) (*FileCacheBody, error) {
file, err := os.Open(path.Join(workdir, fmt.Sprintf("%s.json", cacheFilename)))
if err != nil {
return nil, err
}
bytes, err := io.ReadAll(file)
if err != nil {
return nil, err
}
var fcBody FileCacheBody
err = json.Unmarshal(bytes, &fcBody)
if err != nil {
return nil, err
}
return &fcBody, nil
}
func NewFileCache(workdir string, cacheName string) *FileCache {
fcBody, err := tryRestoreCache(workdir, cacheName)
if err != nil {
logger.Sugar().Error(err.Error())
fcBody = &FileCacheBody{}
}
return &FileCache{
WorkDir: workdir,
CacheFileName: cacheName,
FileCacheBody: fcBody,
}
}
func (fc *FileCache) Put(data *AllScheduleInfo) (persistent bool, err error) {
fc.RWMutex.Lock()
defer fc.RWMutex.Unlock()
// refresh on-memory data
fc.FileCacheBody.Updated = time.Now()
fc.FileCacheBody.Body = data
bytes, err := json.Marshal(*fc.FileCacheBody)
if err != nil {
return false, err
}
file, err := os.Create(filepath.Join(fc.WorkDir, fmt.Sprintf("%s.json", fc.CacheFileName)))
if err != nil {
return false, err
}
nbytes, err := file.Write(bytes)
if len(bytes) != nbytes {
return false, fmt.Errorf("written bytes mismatch: %d, actual: %d", len(bytes), nbytes)
}
return true, nil
}
func (fc *FileCache) Get() *AllScheduleInfo {
fc.RWMutex.RLock()
defer fc.RWMutex.RUnlock()
return fc.FileCacheBody.Body
}
func (fc *FileCache) MaybeGet(ttl time.Duration) *AllScheduleInfo {
fc.RWMutex.RLock()
defer fc.RWMutex.RUnlock()
if fc.IsExpired(ttl) {
return nil
} else {
return fc.Get()
}
}
func (fc *FileCache) IsExpired(ttl time.Duration) bool {
fc.RWMutex.RLock()
defer fc.RWMutex.RUnlock()
return time.Now().After(fc.FileCacheBody.Updated.Add(ttl))
}