-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathcache.go
More file actions
179 lines (149 loc) · 3.94 KB
/
cache.go
File metadata and controls
179 lines (149 loc) · 3.94 KB
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
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
package entity
import (
"bytes"
"compress/gzip"
"context"
"encoding/json"
"fmt"
"io"
"time"
)
// DefaultCacher is the default cache storage instance.
var DefaultCacher Cacher
// Cacheable is an interface for cacheable entity objects.
type Cacheable interface {
CacheOption() CacheOption
}
// Cacher is an interface for cache data storage.
type Cacher interface {
Get(ctx context.Context, key string) ([]byte, error)
Put(ctx context.Context, key string, data []byte, expiration time.Duration) error
Delete(ctx context.Context, key string) error
}
// CacheOption contains cache configuration parameters.
type CacheOption struct {
Cacher Cacher
Key string
Expiration time.Duration
Compress bool
// If true, no cache will be generated.
// This configuration only controls cache generation, not cache reading.
// Because there is not enough information to make a judgment before data is read.
Disable bool
// Some caches constructed elsewhere have field content that is json encoded before entering the cache.
// These field cache results need to be decoded twice to be used.
RecursiveDecode []string
}
func loadCache(ctx context.Context, ent Cacheable) (bool, error) {
opt, err := getCacheOption(ent)
if err != nil {
return false, fmt.Errorf("get option, %w", err)
}
data, err := opt.Cacher.Get(ctx, opt.Key)
if err != nil {
return false, err
} else if len(data) == 0 {
return false, nil
}
if opt.Compress {
zr, err := gzip.NewReader(bytes.NewReader(data))
if err != nil {
return false, fmt.Errorf("uncompress data, %w", err)
}
defer zr.Close()
v, err := io.ReadAll(zr)
if err != nil {
return false, fmt.Errorf("uncompress data, %w", err)
}
data = v
}
if len(opt.RecursiveDecode) > 0 {
fixed, err := recursiveDecode(data, opt.RecursiveDecode)
if err != nil {
return false, fmt.Errorf("recursive decode, %w", err)
} else if fixed != nil {
data = fixed
}
}
if err := json.Unmarshal(data, ent); err != nil {
return false, fmt.Errorf("json decode, %w", err)
}
return true, nil
}
// SaveCache saves an entity to the cache.
func SaveCache(ctx context.Context, ent Cacheable) error {
opt, err := getCacheOption(ent)
if err != nil {
return fmt.Errorf("get option, %w", err)
} else if opt.Disable {
return nil
}
data, err := json.Marshal(ent)
if err != nil {
return fmt.Errorf("json encode, %w", err)
}
if opt.Compress {
var zdata bytes.Buffer
zw := gzip.NewWriter(&zdata)
if _, err := zw.Write(data); err != nil {
return fmt.Errorf("compress cache, %w", err)
}
if err := zw.Close(); err != nil {
return fmt.Errorf("comporess cache, %w", err)
}
data = zdata.Bytes()
}
return opt.Cacher.Put(ctx, opt.Key, data, opt.Expiration)
}
// DeleteCache removes an entity from the cache.
func DeleteCache(ctx context.Context, ent Cacheable) error {
opt, err := getCacheOption(ent)
if err != nil {
return fmt.Errorf("get option, %w", err)
}
return opt.Cacher.Delete(ctx, opt.Key)
}
func getCacheOption(ent Cacheable) (CacheOption, error) {
opt := ent.CacheOption()
if opt.Cacher == nil {
if DefaultCacher == nil {
return opt, fmt.Errorf("nil default cacher")
}
opt.Cacher = DefaultCacher
}
if opt.Key == "" {
return opt, fmt.Errorf("empty cache key")
}
if opt.Expiration == 0 {
opt.Expiration = 5 * time.Minute
}
return opt, nil
}
func recursiveDecode(data []byte, keys []string) ([]byte, error) {
if len(keys) == 0 || len(data) == 0 || data[0] != '{' {
return nil, nil
}
vals := map[string]json.RawMessage{}
if err := json.Unmarshal(data, &vals); err != nil {
return nil, err
}
fixed := false
for _, key := range keys {
if data, ok := vals[key]; ok && len(data) > 0 && data[0] == '"' {
fixed = true
var s string
if err := json.Unmarshal(data, &s); err != nil {
return nil, err
}
vals[key] = []byte(s)
}
}
if !fixed {
return nil, nil
}
encoded, err := json.Marshal(vals)
if err != nil {
return nil, err
}
return encoded, nil
}