flowix 0.1.0__tar.gz → 0.2.0__tar.gz
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.
- flowix-0.2.0/.gitignore +7 -0
- {flowix-0.1.0 → flowix-0.2.0}/PKG-INFO +77 -3
- {flowix-0.1.0 → flowix-0.2.0}/README.md +74 -2
- {flowix-0.1.0 → flowix-0.2.0}/pyproject.toml +5 -1
- {flowix-0.1.0 → flowix-0.2.0}/src/flowix/__init__.py +14 -3
- flowix-0.2.0/src/flowix/algorithm_lua_scripts/fixed_window.py +30 -0
- flowix-0.2.0/src/flowix/algorithm_lua_scripts/leaky_bucket.py +27 -0
- flowix-0.2.0/src/flowix/algorithm_lua_scripts/limiter_script.py +53 -0
- flowix-0.2.0/src/flowix/algorithm_lua_scripts/sliding_counter.py +43 -0
- flowix-0.2.0/src/flowix/algorithm_lua_scripts/sliding_log.py +38 -0
- flowix-0.2.0/src/flowix/algorithm_lua_scripts/token_bucket.py +41 -0
- flowix-0.2.0/src/flowix/engine.py +135 -0
- flowix-0.2.0/src/flowix/interfaces.py +27 -0
- {flowix-0.1.0 → flowix-0.2.0}/src/flowix/limiter.py +27 -1
- flowix-0.2.0/tests/helpers.py +20 -0
- flowix-0.2.0/tests/test_batch.py +186 -0
- flowix-0.2.0/tests/test_limiting.py +232 -0
- {flowix-0.1.0 → flowix-0.2.0}/tests/test_parameters.py +19 -1
- flowix-0.1.0/src/flowix/algorithm_lua_scripts/leaky_bucket.py +0 -45
- flowix-0.1.0/src/flowix/algorithm_lua_scripts/token_bucket.py +0 -51
- flowix-0.1.0/src/flowix/engine.py +0 -73
- flowix-0.1.0/src/flowix/interfaces.py +0 -9
- flowix-0.1.0/tests/test_limiting.py +0 -127
- {flowix-0.1.0 → flowix-0.2.0}/LICENSE +0 -0
- {flowix-0.1.0 → flowix-0.2.0}/src/flowix/algorithm_lua_scripts/__init__.py +0 -0
- {flowix-0.1.0 → flowix-0.2.0}/src/flowix/exceptions.py +0 -0
- {flowix-0.1.0 → flowix-0.2.0}/src/flowix/py.typed +0 -0
- {flowix-0.1.0 → flowix-0.2.0}/tests/conftest.py +0 -0
flowix-0.2.0/.gitignore
ADDED
|
@@ -1,7 +1,9 @@
|
|
|
1
1
|
Metadata-Version: 2.5
|
|
2
2
|
Name: flowix
|
|
3
|
-
Version: 0.
|
|
3
|
+
Version: 0.2.0
|
|
4
4
|
Summary: Distributed, atomic rate limiting for Python, powered by Redis
|
|
5
|
+
Project-URL: Repository, https://github.com/PurpleDNA/flowix
|
|
6
|
+
Project-URL: Issues, https://github.com/PurpleDNA/flowix/issues
|
|
5
7
|
License-Expression: MIT
|
|
6
8
|
License-File: LICENSE
|
|
7
9
|
Keywords: rate-limiter,rate-limiting,redis,throttling
|
|
@@ -27,7 +29,7 @@ Distributed, atomic rate limiting for Python, powered by Redis.
|
|
|
27
29
|
pip install flowix
|
|
28
30
|
```
|
|
29
31
|
|
|
30
|
-
Requires Python 3.10+ and Redis
|
|
32
|
+
Requires Python 3.10+ and Redis 6+.
|
|
31
33
|
|
|
32
34
|
## Quick start
|
|
33
35
|
|
|
@@ -74,6 +76,46 @@ Each request fills the bucket by one, and it drains continuously at `leak_rate`
|
|
|
74
76
|
requests per second. Requests are rejected while the bucket is full. Requests are
|
|
75
77
|
not queued or delayed.
|
|
76
78
|
|
|
79
|
+
### Fixed window
|
|
80
|
+
|
|
81
|
+
```python
|
|
82
|
+
create_limiter("fixed_window", limit=10, window=60)
|
|
83
|
+
```
|
|
84
|
+
|
|
85
|
+
Allows `limit` requests per `window` seconds. A window opens on the first
|
|
86
|
+
allowed request, and the next one opens on the first allowed request after it ends. Up to twice `limit` can
|
|
87
|
+
get through around the moment one window ends and the next begins.
|
|
88
|
+
|
|
89
|
+
### Sliding window log
|
|
90
|
+
|
|
91
|
+
```python
|
|
92
|
+
create_limiter("sliding_log", limit=10, window=60)
|
|
93
|
+
```
|
|
94
|
+
|
|
95
|
+
Never allows more than `limit` requests in any `window` seconds. It stores the time of
|
|
96
|
+
every allowed request, so each key holds up to `limit` entries.
|
|
97
|
+
|
|
98
|
+
### Sliding window counter
|
|
99
|
+
|
|
100
|
+
```python
|
|
101
|
+
create_limiter("sliding_counter", limit=1000, window=60)
|
|
102
|
+
```
|
|
103
|
+
|
|
104
|
+
Estimates the sliding window from two counters, so each key stays small however high
|
|
105
|
+
`limit` is. The estimate assumes the previous window's requests were evenly spread:
|
|
106
|
+
when they came in a burst, up to nearly twice `limit` can get through in `window`
|
|
107
|
+
seconds. Use `sliding_log` when the limit must be exact.
|
|
108
|
+
|
|
109
|
+
### Choosing an algorithm
|
|
110
|
+
|
|
111
|
+
| Algorithm | Stored per key | Most requests in one window | Good for |
|
|
112
|
+
|---|---|---|---|
|
|
113
|
+
| `token` | 2 numbers | `capacity` plus refills | APIs with bursty traffic |
|
|
114
|
+
| `leaky` | 2 numbers | `capacity` plus leaks | Smoothing to a steady rate |
|
|
115
|
+
| `fixed_window` | 2 numbers | Up to 2 × `limit` | Simple quotas |
|
|
116
|
+
| `sliding_log` | Up to `limit` times | Exactly `limit` | Low, strict limits such as logins |
|
|
117
|
+
| `sliding_counter` | 3 numbers | Usually about `limit`, at worst nearly 2 × | High limits on busy endpoints |
|
|
118
|
+
|
|
77
119
|
## Choosing keys
|
|
78
120
|
|
|
79
121
|
A key identifies what is being limited, such as a user or an IP address. Limiters
|
|
@@ -87,6 +129,38 @@ run_limiter("search:user:1", search_limiter, client)
|
|
|
87
129
|
|
|
88
130
|
flowix stores its data in Redis under `flowix:`.
|
|
89
131
|
|
|
132
|
+
## Several limits at once
|
|
133
|
+
|
|
134
|
+
When a request counts towards more than one limit, check them together:
|
|
135
|
+
|
|
136
|
+
```python
|
|
137
|
+
from flowix import run_limiters
|
|
138
|
+
|
|
139
|
+
result = run_limiters([
|
|
140
|
+
("user:1", user_limiter),
|
|
141
|
+
("ip:203.0.113.7", ip_limiter),
|
|
142
|
+
("tenant:9", tenant_limiter),
|
|
143
|
+
], client)
|
|
144
|
+
|
|
145
|
+
if not result["allowed"]:
|
|
146
|
+
print(f"try again in {result['retry_after']} seconds")
|
|
147
|
+
```
|
|
148
|
+
|
|
149
|
+
If any limiter denies the request, the whole batch is denied and **none** of them are
|
|
150
|
+
charged. Everything happens in one Lua script and one round trip, and the limiters can
|
|
151
|
+
use different algorithms.
|
|
152
|
+
|
|
153
|
+
| Key | Type | Meaning |
|
|
154
|
+
|---|---|---|
|
|
155
|
+
| `allowed` | `bool` | Whether every limiter allowed the request |
|
|
156
|
+
| `retry_after` | `int` | Whole seconds until every limiter has room, `0` when allowed |
|
|
157
|
+
| `results` | `list` | One `run_limiter` result per limiter, in the order you gave them |
|
|
158
|
+
|
|
159
|
+
In a denied batch, `results` shows which limiters were the cause. The others say
|
|
160
|
+
`allowed: True` because they had room, not because they were charged.
|
|
161
|
+
|
|
162
|
+
A batch cannot be empty, or repeat the same key with the same algorithm.
|
|
163
|
+
|
|
90
164
|
## Errors
|
|
91
165
|
|
|
92
166
|
Every exception inherits from `FlowixError`.
|
|
@@ -94,7 +168,7 @@ Every exception inherits from `FlowixError`.
|
|
|
94
168
|
| Exception | Raised when |
|
|
95
169
|
|---|---|
|
|
96
170
|
| `InvalidParameterType` | A parameter has the wrong type |
|
|
97
|
-
| `InvalidParameterValue` | A number is zero or negative |
|
|
171
|
+
| `InvalidParameterValue` | A number is zero or negative, or a batch is empty or repeats a limiter |
|
|
98
172
|
| `IncorrectParameters` | Parameters are missing or not accepted by the algorithm |
|
|
99
173
|
| `UnsupportedAlgorithm` | The algorithm does not exist |
|
|
100
174
|
| `BackendFailed` | Redis could not be reached or returned an error |
|
|
@@ -12,7 +12,7 @@ Distributed, atomic rate limiting for Python, powered by Redis.
|
|
|
12
12
|
pip install flowix
|
|
13
13
|
```
|
|
14
14
|
|
|
15
|
-
Requires Python 3.10+ and Redis
|
|
15
|
+
Requires Python 3.10+ and Redis 6+.
|
|
16
16
|
|
|
17
17
|
## Quick start
|
|
18
18
|
|
|
@@ -59,6 +59,46 @@ Each request fills the bucket by one, and it drains continuously at `leak_rate`
|
|
|
59
59
|
requests per second. Requests are rejected while the bucket is full. Requests are
|
|
60
60
|
not queued or delayed.
|
|
61
61
|
|
|
62
|
+
### Fixed window
|
|
63
|
+
|
|
64
|
+
```python
|
|
65
|
+
create_limiter("fixed_window", limit=10, window=60)
|
|
66
|
+
```
|
|
67
|
+
|
|
68
|
+
Allows `limit` requests per `window` seconds. A window opens on the first
|
|
69
|
+
allowed request, and the next one opens on the first allowed request after it ends. Up to twice `limit` can
|
|
70
|
+
get through around the moment one window ends and the next begins.
|
|
71
|
+
|
|
72
|
+
### Sliding window log
|
|
73
|
+
|
|
74
|
+
```python
|
|
75
|
+
create_limiter("sliding_log", limit=10, window=60)
|
|
76
|
+
```
|
|
77
|
+
|
|
78
|
+
Never allows more than `limit` requests in any `window` seconds. It stores the time of
|
|
79
|
+
every allowed request, so each key holds up to `limit` entries.
|
|
80
|
+
|
|
81
|
+
### Sliding window counter
|
|
82
|
+
|
|
83
|
+
```python
|
|
84
|
+
create_limiter("sliding_counter", limit=1000, window=60)
|
|
85
|
+
```
|
|
86
|
+
|
|
87
|
+
Estimates the sliding window from two counters, so each key stays small however high
|
|
88
|
+
`limit` is. The estimate assumes the previous window's requests were evenly spread:
|
|
89
|
+
when they came in a burst, up to nearly twice `limit` can get through in `window`
|
|
90
|
+
seconds. Use `sliding_log` when the limit must be exact.
|
|
91
|
+
|
|
92
|
+
### Choosing an algorithm
|
|
93
|
+
|
|
94
|
+
| Algorithm | Stored per key | Most requests in one window | Good for |
|
|
95
|
+
|---|---|---|---|
|
|
96
|
+
| `token` | 2 numbers | `capacity` plus refills | APIs with bursty traffic |
|
|
97
|
+
| `leaky` | 2 numbers | `capacity` plus leaks | Smoothing to a steady rate |
|
|
98
|
+
| `fixed_window` | 2 numbers | Up to 2 × `limit` | Simple quotas |
|
|
99
|
+
| `sliding_log` | Up to `limit` times | Exactly `limit` | Low, strict limits such as logins |
|
|
100
|
+
| `sliding_counter` | 3 numbers | Usually about `limit`, at worst nearly 2 × | High limits on busy endpoints |
|
|
101
|
+
|
|
62
102
|
## Choosing keys
|
|
63
103
|
|
|
64
104
|
A key identifies what is being limited, such as a user or an IP address. Limiters
|
|
@@ -72,6 +112,38 @@ run_limiter("search:user:1", search_limiter, client)
|
|
|
72
112
|
|
|
73
113
|
flowix stores its data in Redis under `flowix:`.
|
|
74
114
|
|
|
115
|
+
## Several limits at once
|
|
116
|
+
|
|
117
|
+
When a request counts towards more than one limit, check them together:
|
|
118
|
+
|
|
119
|
+
```python
|
|
120
|
+
from flowix import run_limiters
|
|
121
|
+
|
|
122
|
+
result = run_limiters([
|
|
123
|
+
("user:1", user_limiter),
|
|
124
|
+
("ip:203.0.113.7", ip_limiter),
|
|
125
|
+
("tenant:9", tenant_limiter),
|
|
126
|
+
], client)
|
|
127
|
+
|
|
128
|
+
if not result["allowed"]:
|
|
129
|
+
print(f"try again in {result['retry_after']} seconds")
|
|
130
|
+
```
|
|
131
|
+
|
|
132
|
+
If any limiter denies the request, the whole batch is denied and **none** of them are
|
|
133
|
+
charged. Everything happens in one Lua script and one round trip, and the limiters can
|
|
134
|
+
use different algorithms.
|
|
135
|
+
|
|
136
|
+
| Key | Type | Meaning |
|
|
137
|
+
|---|---|---|
|
|
138
|
+
| `allowed` | `bool` | Whether every limiter allowed the request |
|
|
139
|
+
| `retry_after` | `int` | Whole seconds until every limiter has room, `0` when allowed |
|
|
140
|
+
| `results` | `list` | One `run_limiter` result per limiter, in the order you gave them |
|
|
141
|
+
|
|
142
|
+
In a denied batch, `results` shows which limiters were the cause. The others say
|
|
143
|
+
`allowed: True` because they had room, not because they were charged.
|
|
144
|
+
|
|
145
|
+
A batch cannot be empty, or repeat the same key with the same algorithm.
|
|
146
|
+
|
|
75
147
|
## Errors
|
|
76
148
|
|
|
77
149
|
Every exception inherits from `FlowixError`.
|
|
@@ -79,7 +151,7 @@ Every exception inherits from `FlowixError`.
|
|
|
79
151
|
| Exception | Raised when |
|
|
80
152
|
|---|---|
|
|
81
153
|
| `InvalidParameterType` | A parameter has the wrong type |
|
|
82
|
-
| `InvalidParameterValue` | A number is zero or negative |
|
|
154
|
+
| `InvalidParameterValue` | A number is zero or negative, or a batch is empty or repeats a limiter |
|
|
83
155
|
| `IncorrectParameters` | Parameters are missing or not accepted by the algorithm |
|
|
84
156
|
| `UnsupportedAlgorithm` | The algorithm does not exist |
|
|
85
157
|
| `BackendFailed` | Redis could not be reached or returned an error |
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
[project]
|
|
2
2
|
name = "flowix"
|
|
3
|
-
version = "0.
|
|
3
|
+
version = "0.2.0"
|
|
4
4
|
description = "Distributed, atomic rate limiting for Python, powered by Redis"
|
|
5
5
|
readme = "README.md"
|
|
6
6
|
license = "MIT"
|
|
@@ -15,6 +15,10 @@ classifiers = [
|
|
|
15
15
|
"Typing :: Typed",
|
|
16
16
|
]
|
|
17
17
|
|
|
18
|
+
[project.urls]
|
|
19
|
+
Repository = "https://github.com/PurpleDNA/flowix"
|
|
20
|
+
Issues = "https://github.com/PurpleDNA/flowix/issues"
|
|
21
|
+
|
|
18
22
|
[dependency-groups]
|
|
19
23
|
dev = ["pytest>=8"]
|
|
20
24
|
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
from .engine import create_limiter, run_limiter
|
|
1
|
+
from .engine import create_limiter, run_limiter, run_limiters
|
|
2
2
|
from .exceptions import (
|
|
3
3
|
BackendFailed,
|
|
4
4
|
FlowixError,
|
|
@@ -8,15 +8,26 @@ from .exceptions import (
|
|
|
8
8
|
RequestDisallowed,
|
|
9
9
|
UnsupportedAlgorithm,
|
|
10
10
|
)
|
|
11
|
-
from .interfaces import LimitResult
|
|
12
|
-
from .limiter import
|
|
11
|
+
from .interfaces import BatchLimitResult, LimitResult
|
|
12
|
+
from .limiter import (
|
|
13
|
+
FixedWindowLimiter,
|
|
14
|
+
LeakyBucketLimiter,
|
|
15
|
+
SlidingCounterLimiter,
|
|
16
|
+
SlidingLogLimiter,
|
|
17
|
+
TokenBucketLimiter,
|
|
18
|
+
)
|
|
13
19
|
|
|
14
20
|
__all__ = [
|
|
15
21
|
"create_limiter",
|
|
16
22
|
"run_limiter",
|
|
23
|
+
"run_limiters",
|
|
17
24
|
"LeakyBucketLimiter",
|
|
18
25
|
"TokenBucketLimiter",
|
|
26
|
+
"FixedWindowLimiter",
|
|
27
|
+
"SlidingLogLimiter",
|
|
28
|
+
"SlidingCounterLimiter",
|
|
19
29
|
"LimitResult",
|
|
30
|
+
"BatchLimitResult",
|
|
20
31
|
"FlowixError",
|
|
21
32
|
"InvalidParameterType",
|
|
22
33
|
"InvalidParameterValue",
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
fixed_window_lua = """
|
|
2
|
+
algorithms['fixed_window'] = function(key, limit, window)
|
|
3
|
+
local data = redis.call('HMGET', key, 'count', 'start')
|
|
4
|
+
local count = tonumber(data[1])
|
|
5
|
+
local start = tonumber(data[2])
|
|
6
|
+
|
|
7
|
+
-- a window opens on the first allowed request, or the first after the last one ended
|
|
8
|
+
if count == nil or now - start >= window then
|
|
9
|
+
count = 0
|
|
10
|
+
start = now
|
|
11
|
+
end
|
|
12
|
+
|
|
13
|
+
-- clock moved backwards (e.g. failover): restart the window from now. Saved
|
|
14
|
+
-- here because a blocked request returns below without writing anything
|
|
15
|
+
if start > now then
|
|
16
|
+
start = now
|
|
17
|
+
redis.call('HSET', key, 'start', start)
|
|
18
|
+
end
|
|
19
|
+
|
|
20
|
+
if count >= limit then
|
|
21
|
+
-- seconds; rounded up so clients never retry too early
|
|
22
|
+
return nil, math.ceil(window - (now - start))
|
|
23
|
+
end
|
|
24
|
+
|
|
25
|
+
return function()
|
|
26
|
+
redis.call('HSET', key, 'count', count + 1, 'start', start)
|
|
27
|
+
redis.call('EXPIRE', key, math.ceil(window) + 1)
|
|
28
|
+
end
|
|
29
|
+
end
|
|
30
|
+
"""
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
leaky_bucket_lua = """
|
|
2
|
+
algorithms['leaky'] = function(key, capacity, leak_rate)
|
|
3
|
+
local data = redis.call('HMGET', key, 'level', 'last_leak')
|
|
4
|
+
local level = tonumber(data[1]) or 0
|
|
5
|
+
local last_leak = tonumber(data[2]) or now
|
|
6
|
+
|
|
7
|
+
-- clock moved backwards (e.g. failover): restart from now. Saved here
|
|
8
|
+
-- because a blocked request returns below without writing anything
|
|
9
|
+
if last_leak > now then
|
|
10
|
+
last_leak = now
|
|
11
|
+
redis.call('HSET', key, 'last_leak', last_leak)
|
|
12
|
+
end
|
|
13
|
+
|
|
14
|
+
local elapsed = now - last_leak
|
|
15
|
+
level = math.max(0, level - elapsed * leak_rate)
|
|
16
|
+
|
|
17
|
+
if level + 1 > capacity then
|
|
18
|
+
-- seconds; rounded up so clients never retry too early
|
|
19
|
+
return nil, math.ceil((level + 1 - capacity) / leak_rate)
|
|
20
|
+
end
|
|
21
|
+
|
|
22
|
+
return function()
|
|
23
|
+
redis.call('HSET', key, 'level', level + 1, 'last_leak', now)
|
|
24
|
+
redis.call('EXPIRE', key, math.ceil(capacity / leak_rate) + 1)
|
|
25
|
+
end
|
|
26
|
+
end
|
|
27
|
+
"""
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
from .fixed_window import fixed_window_lua
|
|
2
|
+
from .leaky_bucket import leaky_bucket_lua
|
|
3
|
+
from .sliding_counter import sliding_counter_lua
|
|
4
|
+
from .sliding_log import sliding_log_lua
|
|
5
|
+
from .token_bucket import token_bucket_lua
|
|
6
|
+
|
|
7
|
+
# Runs any number of limiters, and charges either all of them or none.
|
|
8
|
+
#
|
|
9
|
+
# Each algorithm adds a function to `algorithms`. Given a key and its parameters, it
|
|
10
|
+
# returns a function that charges the request or, when there is no room for it,
|
|
11
|
+
# nil and the seconds to wait. It must not charge anything itself.
|
|
12
|
+
limiter_script = (
|
|
13
|
+
"""
|
|
14
|
+
local t = redis.call('TIME')
|
|
15
|
+
local now = tonumber(t[1]) + tonumber(t[2]) / 1e6
|
|
16
|
+
|
|
17
|
+
local algorithms = {}
|
|
18
|
+
"""
|
|
19
|
+
+ token_bucket_lua
|
|
20
|
+
+ leaky_bucket_lua
|
|
21
|
+
+ fixed_window_lua
|
|
22
|
+
+ sliding_log_lua
|
|
23
|
+
+ sliding_counter_lua
|
|
24
|
+
+ """
|
|
25
|
+
local charges = {}
|
|
26
|
+
local results = {}
|
|
27
|
+
local all_allowed = true
|
|
28
|
+
|
|
29
|
+
-- ARGV holds four values per key: the algorithm, then its parameters
|
|
30
|
+
for i, key in ipairs(KEYS) do
|
|
31
|
+
local at = (i - 1) * 4
|
|
32
|
+
local check = algorithms[ARGV[at + 1]]
|
|
33
|
+
local charge, retry_after = check(
|
|
34
|
+
key, tonumber(ARGV[at + 2]), tonumber(ARGV[at + 3]), tonumber(ARGV[at + 4])
|
|
35
|
+
)
|
|
36
|
+
if charge then
|
|
37
|
+
charges[i] = charge
|
|
38
|
+
results[i] = {1, 0}
|
|
39
|
+
else
|
|
40
|
+
all_allowed = false
|
|
41
|
+
results[i] = {0, math.max(1, retry_after)}
|
|
42
|
+
end
|
|
43
|
+
end
|
|
44
|
+
|
|
45
|
+
if all_allowed then
|
|
46
|
+
for i = 1, #KEYS do
|
|
47
|
+
charges[i]()
|
|
48
|
+
end
|
|
49
|
+
end
|
|
50
|
+
|
|
51
|
+
return results
|
|
52
|
+
"""
|
|
53
|
+
)
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
sliding_counter_lua = """
|
|
2
|
+
algorithms['sliding_counter'] = function(key, limit, window)
|
|
3
|
+
local current = math.floor(now / window)
|
|
4
|
+
local elapsed = now / window - current
|
|
5
|
+
|
|
6
|
+
local data = redis.call('HMGET', key, 'window', 'curr', 'prev')
|
|
7
|
+
local saved = tonumber(data[1])
|
|
8
|
+
local curr = tonumber(data[2]) or 0
|
|
9
|
+
local prev = tonumber(data[3]) or 0
|
|
10
|
+
|
|
11
|
+
if saved == nil or saved < current - 1 then
|
|
12
|
+
curr = 0
|
|
13
|
+
prev = 0
|
|
14
|
+
elseif saved == current - 1 then
|
|
15
|
+
prev = curr
|
|
16
|
+
curr = 0
|
|
17
|
+
elseif saved > current then
|
|
18
|
+
-- clock moved backwards (e.g. failover): the counts carry over, so moving
|
|
19
|
+
-- the clock never resets a limit. Saved here because a blocked request
|
|
20
|
+
-- returns below without writing anything
|
|
21
|
+
redis.call('HSET', key, 'window', current)
|
|
22
|
+
end
|
|
23
|
+
|
|
24
|
+
if prev * (1 - elapsed) + curr >= limit then
|
|
25
|
+
-- how many windows until the estimate drops to the limit
|
|
26
|
+
local wait
|
|
27
|
+
if curr < limit then
|
|
28
|
+
wait = 1 - (limit - curr) / prev - elapsed
|
|
29
|
+
else
|
|
30
|
+
-- not in this window: in the next one, curr becomes the fading prev
|
|
31
|
+
wait = 1 - elapsed + 1 - limit / curr
|
|
32
|
+
end
|
|
33
|
+
-- seconds; the next whole one, as the estimate must be below the limit. The
|
|
34
|
+
-- extra millisecond covers float error in a wait just under a whole second
|
|
35
|
+
return nil, math.floor(wait * window + 0.001) + 1
|
|
36
|
+
end
|
|
37
|
+
|
|
38
|
+
return function()
|
|
39
|
+
redis.call('HSET', key, 'window', current, 'curr', curr + 1, 'prev', prev)
|
|
40
|
+
redis.call('EXPIRE', key, math.ceil(window * 2) + 1)
|
|
41
|
+
end
|
|
42
|
+
end
|
|
43
|
+
"""
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
sliding_log_lua = """
|
|
2
|
+
algorithms['sliding_log'] = function(key, limit, window)
|
|
3
|
+
local ttl = math.ceil(window) + 1
|
|
4
|
+
|
|
5
|
+
-- a list holding the time of every allowed request, oldest first
|
|
6
|
+
|
|
7
|
+
-- clock moved backwards (e.g. failover): no request can be later than now
|
|
8
|
+
local newest = tonumber(redis.call('LINDEX', key, -1))
|
|
9
|
+
if newest and newest > now then
|
|
10
|
+
local log = redis.call('LRANGE', key, 0, -1)
|
|
11
|
+
redis.call('DEL', key)
|
|
12
|
+
for i = 1, #log do
|
|
13
|
+
redis.call('RPUSH', key, math.min(tonumber(log[i]), now))
|
|
14
|
+
end
|
|
15
|
+
redis.call('EXPIRE', key, ttl)
|
|
16
|
+
end
|
|
17
|
+
|
|
18
|
+
local oldest = tonumber(redis.call('LINDEX', key, 0))
|
|
19
|
+
while oldest and now - oldest >= window do
|
|
20
|
+
redis.call('LPOP', key)
|
|
21
|
+
oldest = tonumber(redis.call('LINDEX', key, 0))
|
|
22
|
+
end
|
|
23
|
+
|
|
24
|
+
local count = redis.call('LLEN', key)
|
|
25
|
+
|
|
26
|
+
if count >= limit then
|
|
27
|
+
-- the request that must leave the window to make room: the oldest, unless
|
|
28
|
+
-- the limit was lowered. Rounded up so clients never retry too early
|
|
29
|
+
local blocking = tonumber(redis.call('LINDEX', key, count - limit))
|
|
30
|
+
return nil, math.ceil(window - (now - blocking))
|
|
31
|
+
end
|
|
32
|
+
|
|
33
|
+
return function()
|
|
34
|
+
redis.call('RPUSH', key, now)
|
|
35
|
+
redis.call('EXPIRE', key, ttl)
|
|
36
|
+
end
|
|
37
|
+
end
|
|
38
|
+
"""
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
token_bucket_lua = """
|
|
2
|
+
algorithms['token'] = function(key, capacity, refill_rate, refill_interval)
|
|
3
|
+
local bucket = redis.call('HMGET', key, 'tokens', 'last_refill')
|
|
4
|
+
local tokens = tonumber(bucket[1])
|
|
5
|
+
local last_refill = tonumber(bucket[2])
|
|
6
|
+
|
|
7
|
+
if tokens == nil then
|
|
8
|
+
tokens = capacity
|
|
9
|
+
last_refill = now
|
|
10
|
+
end
|
|
11
|
+
|
|
12
|
+
-- clock moved backwards (e.g. failover): restart the interval from now. Saved
|
|
13
|
+
-- here because a blocked request returns below without writing anything
|
|
14
|
+
if last_refill > now then
|
|
15
|
+
last_refill = now
|
|
16
|
+
redis.call('HSET', key, 'last_refill', last_refill)
|
|
17
|
+
end
|
|
18
|
+
|
|
19
|
+
local time_passed = now - last_refill
|
|
20
|
+
local refills = math.floor(time_passed / refill_interval)
|
|
21
|
+
|
|
22
|
+
if refills > 0 then
|
|
23
|
+
tokens = math.min(capacity, tokens + (refills * refill_rate))
|
|
24
|
+
last_refill = last_refill + (refills * refill_interval)
|
|
25
|
+
end
|
|
26
|
+
|
|
27
|
+
if tokens < 1 then
|
|
28
|
+
-- seconds until the bucket holds a full token again; a refill_rate below 1
|
|
29
|
+
-- can need several intervals. Rounded up: Redis truncates decimals on return
|
|
30
|
+
local refills_needed = math.ceil((1 - tokens) / refill_rate)
|
|
31
|
+
return nil, math.ceil(last_refill + (refills_needed * refill_interval) - now)
|
|
32
|
+
end
|
|
33
|
+
|
|
34
|
+
return function()
|
|
35
|
+
redis.call('HSET', key, 'tokens', tokens - 1, 'last_refill', last_refill)
|
|
36
|
+
-- tokens only arrive in whole intervals
|
|
37
|
+
local ttl = math.ceil(math.ceil(capacity / refill_rate) * refill_interval) + 10
|
|
38
|
+
redis.call('EXPIRE', key, ttl)
|
|
39
|
+
end
|
|
40
|
+
end
|
|
41
|
+
"""
|
|
@@ -0,0 +1,135 @@
|
|
|
1
|
+
from collections.abc import Iterable
|
|
2
|
+
from typing import Any, Literal, overload
|
|
3
|
+
from redis import Redis
|
|
4
|
+
from redis.exceptions import RedisError
|
|
5
|
+
from .algorithm_lua_scripts.limiter_script import limiter_script
|
|
6
|
+
from .exceptions import (
|
|
7
|
+
BackendFailed,
|
|
8
|
+
IncorrectParameters,
|
|
9
|
+
InvalidParameterType,
|
|
10
|
+
InvalidParameterValue,
|
|
11
|
+
UnsupportedAlgorithm,
|
|
12
|
+
)
|
|
13
|
+
from .interfaces import AlgoType, BatchLimitResult, LimitResult
|
|
14
|
+
from .limiter import (
|
|
15
|
+
FixedWindowLimiter,
|
|
16
|
+
LeakyBucketLimiter,
|
|
17
|
+
SlidingCounterLimiter,
|
|
18
|
+
SlidingLogLimiter,
|
|
19
|
+
TokenBucketLimiter,
|
|
20
|
+
)
|
|
21
|
+
|
|
22
|
+
# names match the functions in the lua script, parameters are in the order they take them
|
|
23
|
+
_ALGORITHMS: dict[str, tuple[type[AlgoType], tuple[str, ...]]] = {
|
|
24
|
+
"leaky": (LeakyBucketLimiter, ("capacity", "leak_rate")),
|
|
25
|
+
"token": (TokenBucketLimiter, ("capacity", "refill_rate", "refill_interval")),
|
|
26
|
+
"fixed_window": (FixedWindowLimiter, ("limit", "window")),
|
|
27
|
+
"sliding_log": (SlidingLogLimiter, ("limit", "window")),
|
|
28
|
+
"sliding_counter": (SlidingCounterLimiter, ("limit", "window")),
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
# the lua script reads this many parameters for every limiter
|
|
32
|
+
_PARAMS_PER_LIMITER = 3
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
@overload
|
|
36
|
+
def create_limiter(
|
|
37
|
+
algo_type: Literal["leaky"],
|
|
38
|
+
*,
|
|
39
|
+
capacity: int,
|
|
40
|
+
leak_rate: float
|
|
41
|
+
) -> LeakyBucketLimiter: ...
|
|
42
|
+
|
|
43
|
+
@overload
|
|
44
|
+
def create_limiter(
|
|
45
|
+
algo_type: Literal["token"],
|
|
46
|
+
*,
|
|
47
|
+
capacity: int,
|
|
48
|
+
refill_rate: float,
|
|
49
|
+
refill_interval: float
|
|
50
|
+
) -> TokenBucketLimiter: ...
|
|
51
|
+
|
|
52
|
+
@overload
|
|
53
|
+
def create_limiter(
|
|
54
|
+
algo_type: Literal["fixed_window"],
|
|
55
|
+
*,
|
|
56
|
+
limit: int,
|
|
57
|
+
window: float
|
|
58
|
+
) -> FixedWindowLimiter: ...
|
|
59
|
+
|
|
60
|
+
@overload
|
|
61
|
+
def create_limiter(
|
|
62
|
+
algo_type: Literal["sliding_log"],
|
|
63
|
+
*,
|
|
64
|
+
limit: int,
|
|
65
|
+
window: float
|
|
66
|
+
) -> SlidingLogLimiter: ...
|
|
67
|
+
|
|
68
|
+
@overload
|
|
69
|
+
def create_limiter(
|
|
70
|
+
algo_type: Literal["sliding_counter"],
|
|
71
|
+
*,
|
|
72
|
+
limit: int,
|
|
73
|
+
window: float
|
|
74
|
+
) -> SlidingCounterLimiter: ...
|
|
75
|
+
|
|
76
|
+
def create_limiter(algo_type: str, **kwargs: Any) -> AlgoType:
|
|
77
|
+
if algo_type not in _ALGORITHMS:
|
|
78
|
+
raise UnsupportedAlgorithm(f"Unsupported algorithm: {algo_type}")
|
|
79
|
+
|
|
80
|
+
limiter_class, params = _ALGORITHMS[algo_type]
|
|
81
|
+
if kwargs.keys() != set(params):
|
|
82
|
+
raise IncorrectParameters(f"{algo_type} takes exactly {sorted(params)}, got {sorted(kwargs)}")
|
|
83
|
+
return limiter_class(**kwargs)
|
|
84
|
+
|
|
85
|
+
def run_limiter(key: str, limiter: AlgoType, client: Redis) -> LimitResult:
|
|
86
|
+
return run_limiters([(key, limiter)], client)["results"][0]
|
|
87
|
+
|
|
88
|
+
def run_limiters(checks: Iterable[tuple[str, AlgoType]], client: Redis) -> BatchLimitResult:
|
|
89
|
+
if not isinstance(checks,Iterable):
|
|
90
|
+
raise InvalidParameterType("checks must be (key, limiter) pairs")
|
|
91
|
+
|
|
92
|
+
keys: list[str] = []
|
|
93
|
+
args: list[str | float] = []
|
|
94
|
+
for check in checks:
|
|
95
|
+
if not isinstance(check,(tuple,list)) or len(check) != 2:
|
|
96
|
+
raise InvalidParameterType("checks must be (key, limiter) pairs")
|
|
97
|
+
key, limiter = check
|
|
98
|
+
if not isinstance(limiter, AlgoType):
|
|
99
|
+
raise InvalidParameterType("limiter must be an algotype")
|
|
100
|
+
if not isinstance(key,str):
|
|
101
|
+
raise InvalidParameterType("key must be a string")
|
|
102
|
+
|
|
103
|
+
algo_type, params = next(
|
|
104
|
+
(name, params)
|
|
105
|
+
for name, (limiter_class, params) in _ALGORITHMS.items()
|
|
106
|
+
if isinstance(limiter, limiter_class)
|
|
107
|
+
)
|
|
108
|
+
redis_key = f"flowix:{algo_type}:{key}"
|
|
109
|
+
if redis_key in keys:
|
|
110
|
+
# both would see the same state, and only one would be charged
|
|
111
|
+
raise InvalidParameterValue(f"{algo_type} limiter with key {key!r} is repeated")
|
|
112
|
+
keys.append(redis_key)
|
|
113
|
+
args.append(algo_type)
|
|
114
|
+
args += [getattr(limiter, param) for param in params]
|
|
115
|
+
args += [0] * (_PARAMS_PER_LIMITER - len(params))
|
|
116
|
+
|
|
117
|
+
if not keys:
|
|
118
|
+
raise InvalidParameterValue("checks must not be empty")
|
|
119
|
+
if not isinstance(client,Redis):
|
|
120
|
+
raise InvalidParameterType("client must be a redis.Redis instance")
|
|
121
|
+
|
|
122
|
+
try:
|
|
123
|
+
raw = client.register_script(limiter_script)(keys=keys, args=args)
|
|
124
|
+
except RedisError as exc:
|
|
125
|
+
raise BackendFailed(f"Redis call failed: {exc}") from exc
|
|
126
|
+
|
|
127
|
+
results: list[LimitResult] = [
|
|
128
|
+
{"allowed": bool(allowed), "retry_after": retry_after}
|
|
129
|
+
for allowed, retry_after in raw
|
|
130
|
+
]
|
|
131
|
+
return {
|
|
132
|
+
"allowed": all(result["allowed"] for result in results),
|
|
133
|
+
"retry_after": max(result["retry_after"] for result in results),
|
|
134
|
+
"results": results,
|
|
135
|
+
}
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
from typing import TypedDict
|
|
2
|
+
from .limiter import (
|
|
3
|
+
FixedWindowLimiter,
|
|
4
|
+
LeakyBucketLimiter,
|
|
5
|
+
SlidingCounterLimiter,
|
|
6
|
+
SlidingLogLimiter,
|
|
7
|
+
TokenBucketLimiter,
|
|
8
|
+
)
|
|
9
|
+
|
|
10
|
+
AlgoType = (
|
|
11
|
+
LeakyBucketLimiter
|
|
12
|
+
| TokenBucketLimiter
|
|
13
|
+
| FixedWindowLimiter
|
|
14
|
+
| SlidingLogLimiter
|
|
15
|
+
| SlidingCounterLimiter
|
|
16
|
+
)
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
class LimitResult(TypedDict):
|
|
20
|
+
allowed: bool
|
|
21
|
+
retry_after: int # seconds, 0 when allowed
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
class BatchLimitResult(TypedDict):
|
|
25
|
+
allowed: bool # True only if every limiter allowed the request
|
|
26
|
+
retry_after: int # seconds until every limiter has room, 0 when allowed
|
|
27
|
+
results: list[LimitResult] # one per limiter, in the order they were given
|