-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathxsetnx_quota.go
106 lines (91 loc) · 2.02 KB
/
xsetnx_quota.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
package andromeda
import (
"context"
"errors"
"fmt"
"time"
)
type xSetNXQuota struct {
cache Cache
getQuotaKey GetQuotaKey
getQuotaExpiration GetQuotaExpiration
getQuota GetQuota
lockIn time.Duration
}
func (q *xSetNXQuota) Do(ctx context.Context, req *QuotaRequest) (err error) {
key, err := q.getQuotaKey.Do(ctx, req)
if errors.Is(err, ErrQuotaNotFound) {
return nil
} else if err != nil {
return
}
exists, err := q.cache.Exists(ctx, key)
if err != nil || exists == 1 {
return
}
lockKey := fmt.Sprintf("%s-lock", key)
succeedLock, err := q.cache.SetNX(ctx, lockKey, 1, q.lockIn)
if err != nil {
return
} else if !succeedLock {
err = fmt.Errorf("%w: %s", ErrLockedKey, lockKey)
return
}
defer func() {
if _, er := q.cache.Del(ctx, lockKey); er != nil {
err = er
}
}()
val, err := q.getQuota.Do(ctx, req)
if err != nil {
return
}
exp, err := q.getQuotaExpiration.Do(ctx, req)
if err != nil {
return
}
_, err = q.cache.SetNX(ctx, key, val, exp)
return
}
// NewXSetNXQuota .
func NewXSetNXQuota(
cache Cache,
getQuotaKey GetQuotaKey,
getQuotaExpiration GetQuotaExpiration,
getQuota GetQuota,
lockIn time.Duration,
) XSetNXQuota {
return &xSetNXQuota{
cache: cache,
getQuotaKey: getQuotaKey,
getQuotaExpiration: getQuotaExpiration,
getQuota: getQuota,
lockIn: lockIn,
}
}
type retryableXSetNXQuota struct {
next XSetNXQuota
maxRetry int
retryIn time.Duration
}
func (q *retryableXSetNXQuota) Do(ctx context.Context, req *QuotaRequest) error {
var err error
for i := 0; i < q.maxRetry; i++ {
err = q.next.Do(ctx, req)
if err == nil {
return nil
}
if i+1 != q.maxRetry {
time.Sleep(q.retryIn)
}
}
return fmt.Errorf("%w: %q", ErrMaxRetryExceeded, err)
}
// NewRetryableXSetNXQuota .
func NewRetryableXSetNXQuota(next XSetNXQuota, maxRetry int, sleepIn time.Duration) XSetNXQuota {
return &retryableXSetNXQuota{
next: next,
maxRetry: maxRetry,
retryIn: sleepIn,
}
}