-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathcache.go
328 lines (283 loc) · 9.85 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
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
package quotacontrol
import (
"context"
"encoding/json"
"errors"
"fmt"
"log/slog"
"time"
"github.com/0xsequence/quotacontrol/proto"
"github.com/go-chi/httprate"
httprateredis "github.com/go-chi/httprate-redis"
"github.com/goware/logger"
"github.com/hashicorp/golang-lru/v2/expirable"
"github.com/redis/go-redis/v9"
)
type QuotaCache interface {
GetProjectQuota(ctx context.Context, projectID uint64) (*proto.AccessQuota, error)
SetProjectQuota(ctx context.Context, quota *proto.AccessQuota) error
DeleteProjectQuota(ctx context.Context, projectID uint64) error
GetAccessQuota(ctx context.Context, accessKey string) (*proto.AccessQuota, error)
SetAccessQuota(ctx context.Context, quota *proto.AccessQuota) error
DeleteAccessQuota(ctx context.Context, accessKey string) error
}
type UsageCache interface {
SetUsage(ctx context.Context, redisKey string, amount int64) error
ClearUsage(ctx context.Context, redisKey string) (bool, error)
PeekUsage(ctx context.Context, redisKey string) (int64, error)
SpendUsage(ctx context.Context, redisKey string, amount, limit int64) (int64, error)
}
type PermissionCache interface {
GetUserPermission(ctx context.Context, projectID uint64, userID string) (proto.UserPermission, *proto.ResourceAccess, error)
SetUserPermission(ctx context.Context, projectID uint64, userID string, userPerm proto.UserPermission, resourceAccess *proto.ResourceAccess) error
DeleteUserPermission(ctx context.Context, projectID uint64, userID string) error
}
type CacheResponse uint8
var (
ErrCachePing = errors.New("quotacontrol: cache ping")
ErrCacheWait = errors.New("quotacontrol: cache wait")
)
const redisKeyPrefix = "quota:"
var (
_ QuotaCache = (*RedisCache)(nil)
_ QuotaCache = (*LRU)(nil)
_ UsageCache = (*RedisCache)(nil)
)
func NewLimitCounter(cfg RedisConfig, logger logger.Logger) httprate.LimitCounter {
if !cfg.Enabled {
return nil
}
return httprateredis.NewCounter(&httprateredis.Config{
Host: cfg.Host,
Port: cfg.Port,
MaxIdle: cfg.MaxIdle,
MaxActive: cfg.MaxActive,
DBIndex: cfg.DBIndex,
OnError: func(err error) {
if logger != nil {
logger.Error("redis counter error", slog.Any("error", err))
}
},
OnFallbackChange: func(fallback bool) {
if logger != nil {
logger.Warn("redis counter fallback", slog.Bool("fallback", fallback))
}
},
})
}
const (
defaultExpRedis = time.Hour
defaultExpLRU = time.Minute
)
func NewRedisCache(redisClient *redis.Client, ttl time.Duration) *RedisCache {
if ttl <= 0 {
ttl = defaultExpRedis
}
return &RedisCache{
client: redisClient,
ttl: ttl,
}
}
type RedisCache struct {
client *redis.Client
ttl time.Duration
}
func (s *RedisCache) GetAccessQuota(ctx context.Context, accessKey string) (*proto.AccessQuota, error) {
return s.getQuota(ctx, accessKey)
}
func (s *RedisCache) DeleteAccessQuota(ctx context.Context, accessKey string) error {
return s.deleteQuota(ctx, accessKey)
}
func (s *RedisCache) SetAccessQuota(ctx context.Context, quota *proto.AccessQuota) error {
return s.setQuota(ctx, quota.AccessKey.AccessKey, quota)
}
func (s *RedisCache) GetProjectQuota(ctx context.Context, projectID uint64) (*proto.AccessQuota, error) {
return s.getQuota(ctx, getProjectKey(projectID))
}
func (s *RedisCache) DeleteProjectQuota(ctx context.Context, projectID uint64) error {
return s.deleteQuota(ctx, getProjectKey(projectID))
}
func (s *RedisCache) SetProjectQuota(ctx context.Context, quota *proto.AccessQuota) error {
return s.setQuota(ctx, getProjectKey(quota.AccessKey.ProjectID), quota)
}
func (s *RedisCache) getQuota(ctx context.Context, key string) (*proto.AccessQuota, error) {
cacheKey := fmt.Sprintf("%s%s", redisKeyPrefix, key)
raw, err := s.client.Get(ctx, cacheKey).Bytes()
if err != nil {
if err == redis.Nil {
return nil, proto.ErrAccessKeyNotFound
}
return nil, fmt.Errorf("get quota: %w", err)
}
var quota proto.AccessQuota
if err := json.Unmarshal(raw, "a); err != nil {
return nil, fmt.Errorf("unmarshal quota: %w", err)
}
return "a, nil
}
func (s *RedisCache) deleteQuota(ctx context.Context, key string) error {
cacheKey := fmt.Sprintf("%s%s", redisKeyPrefix, key)
if err := s.client.Del(ctx, cacheKey).Err(); err != nil {
return fmt.Errorf("delete quota: %w", err)
}
return nil
}
func (s *RedisCache) setQuota(ctx context.Context, key string, quota *proto.AccessQuota) error {
raw, err := json.Marshal(quota)
if err != nil {
return fmt.Errorf("marshal quota: %w", err)
}
cacheKey := fmt.Sprintf("%s%s", redisKeyPrefix, key)
if err := s.client.Set(ctx, cacheKey, raw, s.ttl).Err(); err != nil {
return fmt.Errorf("set quota: %w", err)
}
return nil
}
func (s *RedisCache) SetUsage(ctx context.Context, redisKey string, amount int64) error {
cacheKey := fmt.Sprintf("%s%s", redisKeyPrefix, redisKey)
if err := s.client.Set(ctx, cacheKey, amount, s.ttl).Err(); err != nil {
return fmt.Errorf("set usage: %w", err)
}
return nil
}
func (s *RedisCache) ClearUsage(ctx context.Context, redisKey string) (bool, error) {
cacheKey := fmt.Sprintf("%s%s", redisKeyPrefix, redisKey)
count, err := s.client.Del(ctx, cacheKey).Result()
if err != nil {
return false, fmt.Errorf("clear usage: %w", err)
}
return count != 0, nil
}
func (s *RedisCache) PeekUsage(ctx context.Context, redisKey string) (int64, error) {
const SpecialValue = -1
cacheKey := fmt.Sprintf("%s%s", redisKeyPrefix, redisKey)
v, err := s.client.Get(ctx, cacheKey).Int64()
if err == nil {
if v == SpecialValue {
return 0, ErrCacheWait
}
return v, nil
}
if !errors.Is(err, redis.Nil) {
return 0, fmt.Errorf("peek usage - get: %w", err)
}
ok, err := s.client.SetNX(ctx, cacheKey, SpecialValue, time.Second*2).Result()
if err != nil {
return 0, fmt.Errorf("peek usage - setnx: %w", err)
}
if !ok {
return 0, ErrCacheWait
}
return 0, ErrCachePing
}
func (s *RedisCache) SpendUsage(ctx context.Context, redisKey string, amount, limit int64) (int64, error) {
// NOTE: skip redisKeyPrefix as it's already in PeekCost
v, err := s.PeekUsage(ctx, redisKey)
if err != nil {
return 0, fmt.Errorf("spend usage - peek: %w", err)
}
if v >= limit {
return v, proto.ErrQuotaExceeded
}
cacheKey := fmt.Sprintf("%s%s", redisKeyPrefix, redisKey)
value, err := s.client.IncrBy(ctx, cacheKey, amount).Result()
if err != nil {
return v, fmt.Errorf("spend usage - incrby: %w", err)
}
return value, nil
}
type cacheUserPermission struct {
UserPermission proto.UserPermission `json:"userPerm"`
ResourceAccess *proto.ResourceAccess `json:"resourceAccess"`
}
func (s *RedisCache) GetUserPermission(ctx context.Context, projectID uint64, userID string) (proto.UserPermission, *proto.ResourceAccess, error) {
cacheKey := fmt.Sprintf("%s%s", redisKeyPrefix, getUserPermKey(projectID, userID))
raw, err := s.client.Get(ctx, cacheKey).Bytes()
if err != nil {
if err == redis.Nil {
return proto.UserPermission_UNAUTHORIZED, nil, nil // not found, without error
}
return proto.UserPermission_UNAUTHORIZED, nil, err
}
var v cacheUserPermission
if err := json.Unmarshal(raw, &v); err != nil {
return proto.UserPermission_UNAUTHORIZED, nil, err
}
return v.UserPermission, v.ResourceAccess, nil
}
func (s *RedisCache) SetUserPermission(ctx context.Context, projectID uint64, userID string, userPerm proto.UserPermission, resourceAccess *proto.ResourceAccess) error {
v := cacheUserPermission{
UserPermission: userPerm,
ResourceAccess: resourceAccess,
}
raw, err := json.Marshal(v)
if err != nil {
return err
}
// cache userPermissions for 10 seconds
cacheKey := fmt.Sprintf("%s%s", redisKeyPrefix, getUserPermKey(projectID, userID))
return s.client.Set(ctx, cacheKey, raw, 10*time.Second).Err()
}
func (s *RedisCache) DeleteUserPermission(ctx context.Context, projectID uint64, userID string) error {
cacheKey := fmt.Sprintf("%s%s", redisKeyPrefix, getUserPermKey(projectID, userID))
return s.client.Del(ctx, cacheKey).Err()
}
type LRU struct {
// mem is in-memory lru cache layer
mem *expirable.LRU[string, *proto.AccessQuota]
// backend is pluggable QuotaCache layer, which usually is redis
backend QuotaCache
}
func NewLRU(cacheBackend QuotaCache, size int, ttl time.Duration) *LRU {
if ttl <= 0 {
ttl = defaultExpLRU
}
lruCache := expirable.NewLRU[string, *proto.AccessQuota](size, nil, ttl)
return &LRU{
mem: lruCache,
backend: cacheBackend,
}
}
func (s *LRU) GetAccessQuota(ctx context.Context, accessKey string) (*proto.AccessQuota, error) {
return s.getQuota(ctx, accessKey)
}
func (s *LRU) SetAccessQuota(ctx context.Context, quota *proto.AccessQuota) error {
return s.setQuota(ctx, quota.AccessKey.AccessKey, quota)
}
func (s *LRU) DeleteAccessQuota(ctx context.Context, accessKey string) error {
return s.deleteQuota(ctx, accessKey)
}
func (s *LRU) GetProjectQuota(ctx context.Context, projectID uint64) (*proto.AccessQuota, error) {
return s.getQuota(ctx, getProjectKey(projectID))
}
func (s *LRU) SetProjectQuota(ctx context.Context, quota *proto.AccessQuota) error {
return s.setQuota(ctx, getProjectKey(quota.AccessKey.ProjectID), quota)
}
func (s *LRU) DeleteProjectQuota(ctx context.Context, projectID uint64) error {
return s.deleteQuota(ctx, getProjectKey(projectID))
}
func (s *LRU) getQuota(ctx context.Context, key string) (*proto.AccessQuota, error) {
if aq, ok := s.mem.Get(key); ok {
return aq, nil
}
aq, err := s.backend.GetAccessQuota(ctx, key)
if err != nil {
return nil, err
}
s.mem.Add(key, aq)
return aq, nil
}
func (s *LRU) setQuota(ctx context.Context, key string, aq *proto.AccessQuota) error {
s.mem.Add(key, aq)
return s.backend.SetAccessQuota(ctx, aq)
}
func (s *LRU) deleteQuota(ctx context.Context, key string) error {
s.mem.Remove(key)
return s.backend.DeleteAccessQuota(ctx, key)
}
func getProjectKey(projectID uint64) string {
return fmt.Sprintf("project:%d", projectID)
}
func getUserPermKey(projectID uint64, userID string) string {
return fmt.Sprintf("project:%d:userPerm:%s", projectID, userID)
}