@upstash/ratelimit 2.1.0 → 2.2.1-canary.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,86 @@
1
+ export const fixedWindowLimitScript = `#!lua flags=allow-key-locking
2
+ local key = KEYS[1]
3
+ local id = ARGV[1]
4
+ local window = ARGV[2]
5
+ local incrementBy = tonumber(ARGV[3])
6
+
7
+ redis.call("HSET", key, id, incrementBy)
8
+ local fields = redis.call("HGETALL", key)
9
+ if #fields == 2 and tonumber(fields[2])==incrementBy then
10
+ -- The first time this key is set, and the value will be equal to incrementBy.
11
+ -- So we only need the expire command once
12
+ redis.call("PEXPIRE", key, window)
13
+ end
14
+
15
+ return fields
16
+ `;
17
+ export const fixedWindowRemainingTokensScript = `#!lua flags=allow-key-locking
18
+ local key = KEYS[1]
19
+ local tokens = 0
20
+
21
+ local fields = redis.call("HGETALL", key)
22
+
23
+ return fields
24
+ `;
25
+
26
+ export const slidingWindowLimitScript = `#!lua flags=allow-key-locking
27
+ local currentKey = KEYS[1] -- identifier including prefixes
28
+ local previousKey = KEYS[2] -- key of the previous bucket
29
+ local tokens = tonumber(ARGV[1]) -- tokens per window
30
+ local now = ARGV[2] -- current timestamp in milliseconds
31
+ local window = ARGV[3] -- interval in milliseconds
32
+ local requestId = ARGV[4] -- uuid for this request
33
+ local incrementBy = tonumber(ARGV[5]) -- custom rate, default is 1
34
+
35
+ local currentFields = redis.call("HGETALL", currentKey)
36
+ local requestsInCurrentWindow = 0
37
+ for i = 2, #currentFields, 2 do
38
+ requestsInCurrentWindow = requestsInCurrentWindow + tonumber(currentFields[i])
39
+ end
40
+
41
+ local previousFields = redis.call("HGETALL", previousKey)
42
+ local requestsInPreviousWindow = 0
43
+ for i = 2, #previousFields, 2 do
44
+ requestsInPreviousWindow = requestsInPreviousWindow + tonumber(previousFields[i])
45
+ end
46
+
47
+ local percentageInCurrent = ( now % window) / window
48
+
49
+ -- Only check limit if not refunding (negative rate)
50
+ if incrementBy > 0 and requestsInPreviousWindow * (1 - percentageInCurrent ) + requestsInCurrentWindow + incrementBy > tokens then
51
+ return {currentFields, previousFields, false}
52
+ end
53
+
54
+ redis.call("HSET", currentKey, requestId, incrementBy)
55
+
56
+ if requestsInCurrentWindow == 0 then
57
+ -- The first time this key is set, the value will be equal to incrementBy.
58
+ -- So we only need the expire command once
59
+ redis.call("PEXPIRE", currentKey, window * 2 + 1000) -- Enough time to overlap with a new window + 1 second
60
+ end
61
+ return {currentFields, previousFields, true}
62
+ `;
63
+
64
+ export const slidingWindowRemainingTokensScript = `#!lua flags=allow-key-locking
65
+ local currentKey = KEYS[1] -- identifier including prefixes
66
+ local previousKey = KEYS[2] -- key of the previous bucket
67
+ local now = ARGV[1] -- current timestamp in milliseconds
68
+ local window = ARGV[2] -- interval in milliseconds
69
+
70
+ local currentFields = redis.call("HGETALL", currentKey)
71
+ local requestsInCurrentWindow = 0
72
+ for i = 2, #currentFields, 2 do
73
+ requestsInCurrentWindow = requestsInCurrentWindow + tonumber(currentFields[i])
74
+ end
75
+
76
+ local previousFields = redis.call("HGETALL", previousKey)
77
+ local requestsInPreviousWindow = 0
78
+ for i = 2, #previousFields, 2 do
79
+ requestsInPreviousWindow = requestsInPreviousWindow + tonumber(previousFields[i])
80
+ end
81
+
82
+ local percentageInCurrent = ( now % window) / window
83
+ requestsInPreviousWindow = math.floor(( 1 - percentageInCurrent ) * requestsInPreviousWindow)
84
+
85
+ return requestsInCurrentWindow + requestsInPreviousWindow
86
+ `;
@@ -0,0 +1,23 @@
1
+ export const resetScript = `
2
+ local pattern = KEYS[1]
3
+
4
+ -- Initialize cursor to start from 0
5
+ local cursor = "0"
6
+
7
+ repeat
8
+ -- Scan for keys matching the pattern
9
+ local scan_result = redis.call('SCAN', cursor, 'MATCH', pattern)
10
+
11
+ -- Extract cursor for the next iteration
12
+ cursor = scan_result[1]
13
+
14
+ -- Extract keys from the scan result
15
+ local keys = scan_result[2]
16
+
17
+ for i=1, #keys do
18
+ redis.call('DEL', keys[i])
19
+ end
20
+
21
+ -- Continue scanning until cursor is 0 (end of keyspace)
22
+ until cursor == "0"
23
+ `;
@@ -0,0 +1,237 @@
1
+ export const fixedWindowLimitScript = `#!lua flags=allow-key-locking
2
+ local key = KEYS[1]
3
+ local dynamicLimitKey = KEYS[2] -- optional: key for dynamic limit in redis
4
+ local tokens = tonumber(ARGV[1]) -- default limit
5
+ local window = ARGV[2]
6
+ local incrementBy = ARGV[3] -- increment rate per request at a given value, default is 1
7
+
8
+ -- Check for dynamic limit
9
+ local effectiveLimit = tokens
10
+ if dynamicLimitKey and dynamicLimitKey ~= "" then
11
+ local dynamicLimit = redis.call("GET", dynamicLimitKey)
12
+ if dynamicLimit then
13
+ effectiveLimit = tonumber(dynamicLimit)
14
+ end
15
+ end
16
+
17
+ local r = redis.call("INCRBY", key, incrementBy)
18
+ if r == tonumber(incrementBy) then
19
+ -- The first time this key is set, the value will be equal to incrementBy.
20
+ -- So we only need the expire command once
21
+ redis.call("PEXPIRE", key, window)
22
+ end
23
+
24
+ return {r, effectiveLimit}
25
+ `;
26
+
27
+ export const fixedWindowRemainingTokensScript = `#!lua flags=allow-key-locking
28
+ local key = KEYS[1]
29
+ local dynamicLimitKey = KEYS[2] -- optional: key for dynamic limit in redis
30
+ local tokens = tonumber(ARGV[1]) -- default limit
31
+
32
+ -- Check for dynamic limit
33
+ local effectiveLimit = tokens
34
+ if dynamicLimitKey and dynamicLimitKey ~= "" then
35
+ local dynamicLimit = redis.call("GET", dynamicLimitKey)
36
+ if dynamicLimit then
37
+ effectiveLimit = tonumber(dynamicLimit)
38
+ end
39
+ end
40
+
41
+ local value = redis.call('GET', key)
42
+ local usedTokens = 0
43
+ if value then
44
+ usedTokens = tonumber(value)
45
+ end
46
+
47
+ return {effectiveLimit - usedTokens, effectiveLimit}
48
+ `;
49
+
50
+ export const slidingWindowLimitScript = `#!lua flags=allow-key-locking
51
+ local currentKey = KEYS[1] -- identifier including prefixes
52
+ local previousKey = KEYS[2] -- key of the previous bucket
53
+ local dynamicLimitKey = KEYS[3] -- optional: key for dynamic limit in redis
54
+ local tokens = tonumber(ARGV[1]) -- default tokens per window
55
+ local now = ARGV[2] -- current timestamp in milliseconds
56
+ local window = ARGV[3] -- interval in milliseconds
57
+ local incrementBy = tonumber(ARGV[4]) -- increment rate per request at a given value, default is 1
58
+
59
+ -- Check for dynamic limit
60
+ local effectiveLimit = tokens
61
+ if dynamicLimitKey and dynamicLimitKey ~= "" then
62
+ local dynamicLimit = redis.call("GET", dynamicLimitKey)
63
+ if dynamicLimit then
64
+ effectiveLimit = tonumber(dynamicLimit)
65
+ end
66
+ end
67
+
68
+ local requestsInCurrentWindow = redis.call("GET", currentKey)
69
+ if requestsInCurrentWindow == false then
70
+ requestsInCurrentWindow = 0
71
+ end
72
+
73
+ local requestsInPreviousWindow = redis.call("GET", previousKey)
74
+ if requestsInPreviousWindow == false then
75
+ requestsInPreviousWindow = 0
76
+ end
77
+ local percentageInCurrent = ( now % window ) / window
78
+ -- weighted requests to consider from the previous window
79
+ requestsInPreviousWindow = math.floor(( 1 - percentageInCurrent ) * requestsInPreviousWindow)
80
+
81
+ -- Only check limit if not refunding (negative rate)
82
+ if incrementBy > 0 and requestsInPreviousWindow + requestsInCurrentWindow >= effectiveLimit then
83
+ return {-1, effectiveLimit}
84
+ end
85
+
86
+ local newValue = redis.call("INCRBY", currentKey, incrementBy)
87
+ if newValue == incrementBy then
88
+ -- The first time this key is set, the value will be equal to incrementBy.
89
+ -- So we only need the expire command once
90
+ redis.call("PEXPIRE", currentKey, window * 2 + 1000) -- Enough time to overlap with a new window + 1 second
91
+ end
92
+ return {effectiveLimit - ( newValue + requestsInPreviousWindow ), effectiveLimit}
93
+ `;
94
+
95
+ export const slidingWindowRemainingTokensScript = `#!lua flags=allow-key-locking
96
+ local currentKey = KEYS[1] -- identifier including prefixes
97
+ local previousKey = KEYS[2] -- key of the previous bucket
98
+ local dynamicLimitKey = KEYS[3] -- optional: key for dynamic limit in redis
99
+ local tokens = tonumber(ARGV[1]) -- default tokens per window
100
+ local now = ARGV[2] -- current timestamp in milliseconds
101
+ local window = ARGV[3] -- interval in milliseconds
102
+
103
+ -- Check for dynamic limit
104
+ local effectiveLimit = tokens
105
+ if dynamicLimitKey and dynamicLimitKey ~= "" then
106
+ local dynamicLimit = redis.call("GET", dynamicLimitKey)
107
+ if dynamicLimit then
108
+ effectiveLimit = tonumber(dynamicLimit)
109
+ end
110
+ end
111
+
112
+ local requestsInCurrentWindow = redis.call("GET", currentKey)
113
+ if requestsInCurrentWindow == false then
114
+ requestsInCurrentWindow = 0
115
+ end
116
+
117
+ local requestsInPreviousWindow = redis.call("GET", previousKey)
118
+ if requestsInPreviousWindow == false then
119
+ requestsInPreviousWindow = 0
120
+ end
121
+
122
+ local percentageInCurrent = ( now % window ) / window
123
+ -- weighted requests to consider from the previous window
124
+ requestsInPreviousWindow = math.floor(( 1 - percentageInCurrent ) * requestsInPreviousWindow)
125
+
126
+ local usedTokens = requestsInPreviousWindow + requestsInCurrentWindow
127
+ return {effectiveLimit - usedTokens, effectiveLimit}
128
+ `;
129
+
130
+ export const tokenBucketLimitScript = `#!lua flags=allow-key-locking
131
+ local key = KEYS[1] -- identifier including prefixes
132
+ local dynamicLimitKey = KEYS[2] -- optional: key for dynamic limit in redis
133
+ local maxTokens = tonumber(ARGV[1]) -- default maximum number of tokens
134
+ local interval = tonumber(ARGV[2]) -- size of the window in milliseconds
135
+ local refillRate = tonumber(ARGV[3]) -- how many tokens are refilled after each interval
136
+ local now = tonumber(ARGV[4]) -- current timestamp in milliseconds
137
+ local incrementBy = tonumber(ARGV[5]) -- how many tokens to consume, default is 1
138
+
139
+ -- Check for dynamic limit
140
+ local effectiveLimit = maxTokens
141
+ if dynamicLimitKey and dynamicLimitKey ~= "" then
142
+ local dynamicLimit = redis.call("GET", dynamicLimitKey)
143
+ if dynamicLimit then
144
+ effectiveLimit = tonumber(dynamicLimit)
145
+ end
146
+ end
147
+
148
+ local bucket = redis.call("HMGET", key, "refilledAt", "tokens")
149
+
150
+ local refilledAt
151
+ local tokens
152
+
153
+ if bucket[1] == false then
154
+ refilledAt = now
155
+ tokens = effectiveLimit
156
+ else
157
+ refilledAt = tonumber(bucket[1])
158
+ tokens = tonumber(bucket[2])
159
+ end
160
+
161
+ if now >= refilledAt + interval then
162
+ local numRefills = math.floor((now - refilledAt) / interval)
163
+ tokens = math.min(effectiveLimit, tokens + numRefills * refillRate)
164
+
165
+ refilledAt = refilledAt + numRefills * interval
166
+ end
167
+
168
+ -- Only reject when consuming (not refunding) and there are not enough tokens
169
+ -- for this request. Checking tokens == 0 only covered incrementBy == 1: with
170
+ -- a larger rate (e.g. 2 tokens left, incrementBy 5) the request fell through,
171
+ -- drove tokens negative and still wrote it back, so a rejected request
172
+ -- consumed tokens and a single large rate could lock the identifier out.
173
+ if incrementBy > 0 and tokens < incrementBy then
174
+ return {-1, refilledAt + interval, effectiveLimit}
175
+ end
176
+
177
+ local remaining = tokens - incrementBy
178
+ local expireAt = math.ceil(((effectiveLimit - remaining) / refillRate)) * interval
179
+
180
+ redis.call("HSET", key, "refilledAt", refilledAt, "tokens", remaining)
181
+
182
+ if (expireAt > 0) then
183
+ redis.call("PEXPIRE", key, expireAt)
184
+ end
185
+ return {remaining, refilledAt + interval, effectiveLimit}
186
+ `;
187
+
188
+ export const tokenBucketIdentifierNotFound = -1
189
+
190
+ export const tokenBucketRemainingTokensScript = `#!lua flags=allow-key-locking
191
+ local key = KEYS[1]
192
+ local dynamicLimitKey = KEYS[2] -- optional: key for dynamic limit in redis
193
+ local maxTokens = tonumber(ARGV[1]) -- default maximum number of tokens
194
+
195
+ -- Check for dynamic limit
196
+ local effectiveLimit = maxTokens
197
+ if dynamicLimitKey and dynamicLimitKey ~= "" then
198
+ local dynamicLimit = redis.call("GET", dynamicLimitKey)
199
+ if dynamicLimit then
200
+ effectiveLimit = tonumber(dynamicLimit)
201
+ end
202
+ end
203
+
204
+ local bucket = redis.call("HMGET", key, "refilledAt", "tokens")
205
+
206
+ if bucket[1] == false then
207
+ return {effectiveLimit, ${tokenBucketIdentifierNotFound}, effectiveLimit}
208
+ end
209
+
210
+ return {tonumber(bucket[2]), tonumber(bucket[1]), effectiveLimit}
211
+ `;
212
+
213
+ export const cachedFixedWindowLimitScript = `#!lua flags=allow-key-locking
214
+ local key = KEYS[1]
215
+ local window = ARGV[1]
216
+ local incrementBy = ARGV[2] -- increment rate per request at a given value, default is 1
217
+
218
+ local r = redis.call("INCRBY", key, incrementBy)
219
+ if r == incrementBy then
220
+ -- The first time this key is set, the value will be equal to incrementBy.
221
+ -- So we only need the expire command once
222
+ redis.call("PEXPIRE", key, window)
223
+ end
224
+
225
+ return r
226
+ `;
227
+
228
+ export const cachedFixedWindowRemainingTokenScript = `#!lua flags=allow-key-locking
229
+ local key = KEYS[1]
230
+ local tokens = 0
231
+
232
+ local value = redis.call('GET', key)
233
+ if value then
234
+ tokens = value
235
+ end
236
+ return tokens
237
+ `;