-
Notifications
You must be signed in to change notification settings - Fork 0
/
driver_gorm.go
187 lines (157 loc) · 4.38 KB
/
driver_gorm.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
package ratelimiter
import (
"context"
"fmt"
"strconv"
"strings"
"time"
"github.com/go-sql-driver/mysql"
"github.com/jackc/pgx/v5/pgconn"
"github.com/pkg/errors"
"gorm.io/gorm"
)
type KV struct {
Key string `json:"key" gorm:"primaryKey;not null;"`
Value string `json:"value" gorm:"not null;"`
}
type GormDriver struct {
db *gorm.DB
rawQuery string
}
// NewGormDriver returns a Driver that uses Gorm as the storage.
// Sometimes you may need to auto migrate the KV table, you can use `InitGormDriver` instead.
func NewGormDriver(db *gorm.DB) *GormDriver {
d := &GormDriver{
db: db,
}
var currentTimestampQuery string
switch db.Dialector.Name() {
case "mysql":
currentTimestampQuery = "CURRENT_TIMESTAMP(6)"
case "postgres":
currentTimestampQuery = "clock_timestamp()"
default:
// Fallback to a generic solution or handle other databases if needed
currentTimestampQuery = "CURRENT_TIMESTAMP"
}
d.rawQuery = fmt.Sprintf(`
WITH kv_select AS (
SELECT * FROM kvs WHERE key = ? FOR UPDATE
)
SELECT kv.*, %s AS now
FROM (SELECT 1) AS dummy
LEFT JOIN kv_select AS kv ON kv.key = ?;
`, currentTimestampQuery)
return d
}
// InitGormDriver initializes a GormDriver with the provided Gorm DB.
// Sometimes you may not need to auto migrate the KV table, you can use `NewGormDriver` instead.
func InitGormDriver(ctx context.Context, db *gorm.DB) (*GormDriver, error) {
if err := db.AutoMigrate(&KV{}); err != nil {
return nil, errors.Wrap(err, "ratelimiter: failed to migrate kv")
}
return NewGormDriver(db), nil
}
type kvWrapper struct {
KV
Now time.Time
}
type ctxKeyAfterQuery struct{}
func isDuplicateKeyError(err error) bool {
if err == nil {
return false
}
var pqErr *pgconn.PgError
if errors.As(err, &pqErr) {
return pqErr.Code == "23505"
}
var mysqlErr *mysql.MySQLError
if errors.As(err, &mysqlErr) {
return mysqlErr.Number == 1062
}
errMsg := err.Error()
return strings.Contains(errMsg, "SQLSTATE 23505")
}
func (d *GormDriver) Reserve(ctx context.Context, req *ReserveRequest) (*Reservation, error) {
return d.reserve(ctx, req, 0)
}
func (d *GormDriver) reserve(ctx context.Context, req *ReserveRequest, idx int) (*Reservation, error) {
if req.Key == "" || req.DurationPerToken <= 0 || req.Burst <= 0 || req.Tokens <= 0 || req.Tokens > req.Burst {
return nil, errors.Wrapf(ErrInvalidParameters, "%v", req)
}
select {
case <-ctx.Done():
return nil, errors.Wrap(ctx.Err(), "ratelimiter: context done")
default:
}
var now time.Time
if Test {
nowFunc, exists := NowFuncFromContextForTest(ctx)
if exists {
now = nowFunc().UTC() // stripMono
}
}
var timeBase time.Time
var timeToAct time.Time
var ok bool
err := d.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
var kv kvWrapper
if err := tx.Raw(d.rawQuery, req.Key, req.Key).Scan(&kv).Error; err != nil {
return errors.Wrap(err, "ratelimiter: failed to get kv")
}
if Test {
afterQuery, ok := ctx.Value(ctxKeyAfterQuery{}).(func(kv kvWrapper))
if ok {
afterQuery(kv)
}
}
if now.IsZero() {
now = kv.Now // use db time
}
resetValue := now.Add(-time.Duration(req.Burst) * req.DurationPerToken)
if kv.Key == "" { // not found
timeBase = resetValue
if err := tx.Create(&KV{
Key: req.Key,
Value: strconv.FormatInt(timeBase.UnixMicro(), 10),
}).Error; err != nil {
return errors.Wrap(err, "ratelimiter: failed to create kv")
}
} else {
unixMicroBase, err := strconv.ParseInt(kv.Value, 10, 64)
if err != nil {
return errors.Wrap(err, "ratelimiter: failed to parse base time")
}
timeBase = time.UnixMicro(unixMicroBase)
if timeBase.Before(resetValue) {
timeBase = resetValue
}
}
tokensDuration := req.DurationPerToken * time.Duration(req.Tokens)
timeToAct = timeBase.Add(tokensDuration).UTC()
if timeToAct.After(now.Add(req.MaxFutureReserve)) {
ok = false
return nil
}
if err := tx.Model(&KV{}).Where("key = ?", req.Key).Update(
"value", strconv.FormatInt(timeToAct.UnixMicro(), 10),
).Error; err != nil {
return errors.Wrap(err, "ratelimiter: failed to save time to act")
}
ok = true
return nil
})
if err != nil {
// retry once if duplicate key errorf
if idx == 0 && isDuplicateKeyError(err) {
return d.reserve(ctx, req, idx+1)
}
return nil, err
}
return &Reservation{
ReserveRequest: req,
OK: ok,
TimeToAct: timeToAct,
Now: now,
}, nil
}