/
cache.go
252 lines (213 loc) · 6.79 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
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
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
package source
import (
"context"
"encoding/json"
"fmt"
"github.com/jollyboss123/tcg_my-server/config"
"github.com/jollyboss123/tcg_my-server/pkg/game"
"github.com/redis/go-redis/v9"
"log/slog"
"strings"
"sync"
)
type cachedSource struct {
services []ScrapeService
gs game.Service
cache *redis.Client
cfg *config.Config
logger *slog.Logger
}
func NewCachedScrapeService(cache *redis.Client, cfg *config.Config, logger *slog.Logger, gs game.Service, service ...ScrapeService) ScrapeService {
child := logger.With(slog.String("api", "cached-scrape"))
return &cachedSource{
services: service,
cache: cache,
cfg: cfg,
logger: child,
gs: gs,
}
}
// List fetches cards based on the provided query from the cache or from external services.
// If the cache has entries for the given query, it fetches from the cache; otherwise, it fetches from services.
func (c *cachedSource) List(ctx context.Context, query, game string) ([]*Card, error) {
query = strings.ToUpper(query)
_, err := c.gs.Fetch(ctx, game)
if err != nil {
c.logger.Error("fetch game", slog.String("error", err.Error()), slog.String("query", query), slog.String("game", game))
return make([]*Card, 0), err
}
if c.isQueryCached(ctx, query, game) {
c.logger.Info("cache hit", slog.String("query", query))
return c.fetchFromDataCache(ctx, query, game)
}
c.logger.Info("cache miss", slog.String("query", query))
cards, err := c.fetchAndCache(ctx, query, game)
if err != nil {
return nil, err
}
return cards, nil
}
func (c *cachedSource) isQueryCached(ctx context.Context, query, game string) bool {
exists, err := c.cache.SIsMember(ctx, fmt.Sprintf("query:%s", game), query).Result()
return err == nil && exists
}
func (c *cachedSource) cacheQuery(ctx context.Context, query, game string) error {
err := c.cache.SAdd(ctx, fmt.Sprintf("query:%s", game), query).Err()
if err != nil {
return err
}
err = c.cache.Expire(ctx, fmt.Sprintf("query:%s", game), c.cfg.Cache.CacheTime).Err()
if err != nil {
return err
}
return nil
}
func (c *cachedSource) fetchFromDataCache(ctx context.Context, query, game string) ([]*Card, error) {
var cards []*Card
var mu sync.Mutex
setKey := fmt.Sprintf("game:identifiers:%s", game)
hashKey := fmt.Sprintf("game:data:%s", game)
patterns := []string{
fmt.Sprintf("*||*||*%s*", query), // for code or booster
fmt.Sprintf("*||*%s*||*", query), // for name
}
wg := &sync.WaitGroup{}
wg.Add(len(patterns))
errCh := make(chan error, len(patterns))
for _, pattern := range patterns {
go func(p string) {
defer wg.Done()
cs, err := c.sscan(ctx, setKey, hashKey, p)
if err != nil {
c.logger.Error("redis scan", slog.String("error", err.Error()), slog.String("pattern", p))
errCh <- err
return
}
if len(cs) <= 0 {
return
}
c.logger.Info("cache hit", slog.String("query", query), slog.String("pattern", p), slog.Int("total", len(cs)))
mu.Lock()
cards = append(cards, cs...)
mu.Unlock()
}(pattern)
}
wg.Wait()
close(errCh)
if len(errCh) > 0 {
return nil, <-errCh
}
if len(cards) > 0 {
return cards, nil
}
return cards, nil
}
func (c *cachedSource) fetchAndCache(ctx context.Context, query, game string) ([]*Card, error) {
var cards []*Card
var mu sync.Mutex
wg := &sync.WaitGroup{}
wg.Add(len(c.services))
for _, service := range c.services {
go func(s ScrapeService) {
defer wg.Done()
cs, err := s.List(ctx, query, game)
if err != nil {
c.logger.Error("list card", slog.String("error", err.Error()), slog.String("query", query))
return
}
mu.Lock()
cards = append(cards, cs...)
mu.Unlock()
}(service)
}
wg.Wait()
if len(cards) == 0 {
c.logger.Info("no cards found", slog.String("query", query))
return cards, nil
}
// Assign scores based on rarity. Assuming the list is sorted such that
// the rarest card is first and the least rare card is last.
// The rarer the card, the higher the score.
for idx, card := range cards {
card.Score = len(cards) - idx
_ = c.cacheQuery(ctx, card.JpName, game)
_ = c.cacheQuery(ctx, card.Code, game)
uID := fmt.Sprintf("%s||%s||%s", card.Rarity, card.JpName, card.Code)
setKey := fmt.Sprintf("game:identifiers:%s", game)
hashKey := fmt.Sprintf("game:data:%s", game)
err := c.cache.SAdd(ctx, setKey, uID).Err()
if err != nil {
c.logger.Warn("set add cache", slog.String("error", err.Error()), slog.String("query", query))
continue
}
err = c.cache.Expire(ctx, setKey, c.cfg.Cache.CacheTime).Err()
if err != nil {
c.logger.Warn("set sets cache expiry", slog.String("error", err.Error()), slog.String("query", query))
continue
}
data, err := json.Marshal(card)
if err != nil {
c.logger.Warn("marshal cache data", slog.String("error", err.Error()), slog.String("query", query))
continue
}
err = c.cache.HSet(ctx, hashKey, uID, data).Err()
if err != nil {
c.logger.Warn("cache entry", slog.String("error", err.Error()), slog.String("query", query))
continue
}
err = c.cache.Expire(ctx, hashKey, c.cfg.Cache.CacheTime).Err()
if err != nil {
c.logger.Warn("set hash set cache expiry", slog.String("error", err.Error()), slog.String("query", query))
continue
}
}
c.logger.Info("cache entry", slog.String("query", query), slog.Int("total", len(cards)))
_ = c.cacheQuery(ctx, query, game)
return cards, nil
}
func (c *cachedSource) scan(ctx context.Context, pattern string) ([]*Card, error) {
var cards []*Card
cursor := uint64(0)
iter := c.cache.Scan(ctx, cursor, pattern, 0).Iterator()
for iter.Next(ctx) {
c.logger.Debug("key found", slog.String("key", iter.Val()))
var card *Card
val, err := c.cache.Get(ctx, iter.Val()).Result()
if err != nil {
c.logger.Warn("cache get", slog.String("error", err.Error()), slog.String("key", iter.Val()))
continue
}
err = json.Unmarshal([]byte(val), &card)
if err == nil {
cards = append(cards, card)
}
}
if err := iter.Err(); err != nil {
c.logger.Error("iterate scan", slog.String("error", err.Error()), slog.String("key", iter.Val()))
return nil, err
}
return cards, nil
}
func (c *cachedSource) sscan(ctx context.Context, setKey, hashKey, pattern string) ([]*Card, error) {
var cards []*Card
cursor := uint64(0)
iter := c.cache.SScan(ctx, setKey, cursor, pattern, 0).Iterator()
for iter.Next(ctx) {
c.logger.Debug("key found", slog.String("key", iter.Val()))
var card *Card
val, err := c.cache.HGet(ctx, hashKey, iter.Val()).Result()
if err != nil {
c.logger.Warn("cache get", slog.String("error", err.Error()), slog.String("key", iter.Val()))
continue
}
err = json.Unmarshal([]byte(val), &card)
if err == nil {
cards = append(cards, card)
}
}
if err := iter.Err(); err != nil {
c.logger.Error("iterate scan", slog.String("error", err.Error()), slog.String("key", iter.Val()))
return nil, err
}
return cards, nil
}