flowix 0.1.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.1.0/LICENSE +21 -0
- flowix-0.1.0/PKG-INFO +129 -0
- flowix-0.1.0/README.md +114 -0
- flowix-0.1.0/pyproject.toml +29 -0
- flowix-0.1.0/src/flowix/__init__.py +27 -0
- flowix-0.1.0/src/flowix/algorithm_lua_scripts/__init__.py +0 -0
- flowix-0.1.0/src/flowix/algorithm_lua_scripts/leaky_bucket.py +45 -0
- flowix-0.1.0/src/flowix/algorithm_lua_scripts/token_bucket.py +51 -0
- flowix-0.1.0/src/flowix/engine.py +73 -0
- flowix-0.1.0/src/flowix/exceptions.py +27 -0
- flowix-0.1.0/src/flowix/interfaces.py +9 -0
- flowix-0.1.0/src/flowix/limiter.py +40 -0
- flowix-0.1.0/src/flowix/py.typed +0 -0
- flowix-0.1.0/tests/conftest.py +25 -0
- flowix-0.1.0/tests/test_limiting.py +127 -0
- flowix-0.1.0/tests/test_parameters.py +79 -0
flowix-0.1.0/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 flowix
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
flowix-0.1.0/PKG-INFO
ADDED
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: flowix
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Distributed, atomic rate limiting for Python, powered by Redis
|
|
5
|
+
License-Expression: MIT
|
|
6
|
+
License-File: LICENSE
|
|
7
|
+
Keywords: rate-limiter,rate-limiting,redis,throttling
|
|
8
|
+
Classifier: Development Status :: 3 - Alpha
|
|
9
|
+
Classifier: Intended Audience :: Developers
|
|
10
|
+
Classifier: Programming Language :: Python :: 3
|
|
11
|
+
Classifier: Typing :: Typed
|
|
12
|
+
Requires-Python: >=3.10
|
|
13
|
+
Requires-Dist: redis>=4.3.4
|
|
14
|
+
Description-Content-Type: text/markdown
|
|
15
|
+
|
|
16
|
+
# flowix
|
|
17
|
+
|
|
18
|
+
Distributed, atomic rate limiting for Python, powered by Redis.
|
|
19
|
+
|
|
20
|
+
- **Distributed:** every app server using the same Redis shares the same limits.
|
|
21
|
+
- **Atomic:** each check is a single Lua script, so simultaneous requests can't slip past a limit.
|
|
22
|
+
- **One clock:** timing comes from the Redis server, not from your app servers.
|
|
23
|
+
|
|
24
|
+
## Install
|
|
25
|
+
|
|
26
|
+
```bash
|
|
27
|
+
pip install flowix
|
|
28
|
+
```
|
|
29
|
+
|
|
30
|
+
Requires Python 3.10+ and Redis 5+.
|
|
31
|
+
|
|
32
|
+
## Quick start
|
|
33
|
+
|
|
34
|
+
```python
|
|
35
|
+
from redis import Redis
|
|
36
|
+
from flowix import create_limiter, run_limiter
|
|
37
|
+
|
|
38
|
+
client = Redis.from_url("redis://localhost:6379")
|
|
39
|
+
limiter = create_limiter("token", capacity=3, refill_rate=1, refill_interval=10)
|
|
40
|
+
|
|
41
|
+
result = run_limiter("user:1", limiter, client)
|
|
42
|
+
|
|
43
|
+
if result["allowed"]:
|
|
44
|
+
print("go ahead")
|
|
45
|
+
else:
|
|
46
|
+
print(f"try again in {result['retry_after']} seconds")
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
`run_limiter` returns a dict:
|
|
50
|
+
|
|
51
|
+
| Key | Type | Meaning |
|
|
52
|
+
|---|---|---|
|
|
53
|
+
| `allowed` | `bool` | Whether the request may proceed |
|
|
54
|
+
| `retry_after` | `int` | Whole seconds until a request can be allowed, `0` when allowed |
|
|
55
|
+
|
|
56
|
+
## Algorithms
|
|
57
|
+
|
|
58
|
+
### Token bucket
|
|
59
|
+
|
|
60
|
+
```python
|
|
61
|
+
create_limiter("token", capacity=10, refill_rate=5, refill_interval=60)
|
|
62
|
+
```
|
|
63
|
+
|
|
64
|
+
Allows bursts of up to `capacity` requests, then adds `refill_rate` tokens every
|
|
65
|
+
`refill_interval` seconds. Each request uses one token.
|
|
66
|
+
|
|
67
|
+
### Leaky bucket
|
|
68
|
+
|
|
69
|
+
```python
|
|
70
|
+
create_limiter("leaky", capacity=10, leak_rate=2)
|
|
71
|
+
```
|
|
72
|
+
|
|
73
|
+
Each request fills the bucket by one, and it drains continuously at `leak_rate`
|
|
74
|
+
requests per second. Requests are rejected while the bucket is full. Requests are
|
|
75
|
+
not queued or delayed.
|
|
76
|
+
|
|
77
|
+
## Choosing keys
|
|
78
|
+
|
|
79
|
+
A key identifies what is being limited, such as a user or an IP address. Limiters
|
|
80
|
+
using the same algorithm and the same key share one bucket, so give each limit its
|
|
81
|
+
own key:
|
|
82
|
+
|
|
83
|
+
```python
|
|
84
|
+
run_limiter("login:user:1", login_limiter, client)
|
|
85
|
+
run_limiter("search:user:1", search_limiter, client)
|
|
86
|
+
```
|
|
87
|
+
|
|
88
|
+
flowix stores its data in Redis under `flowix:`.
|
|
89
|
+
|
|
90
|
+
## Errors
|
|
91
|
+
|
|
92
|
+
Every exception inherits from `FlowixError`.
|
|
93
|
+
|
|
94
|
+
| Exception | Raised when |
|
|
95
|
+
|---|---|
|
|
96
|
+
| `InvalidParameterType` | A parameter has the wrong type |
|
|
97
|
+
| `InvalidParameterValue` | A number is zero or negative |
|
|
98
|
+
| `IncorrectParameters` | Parameters are missing or not accepted by the algorithm |
|
|
99
|
+
| `UnsupportedAlgorithm` | The algorithm does not exist |
|
|
100
|
+
| `BackendFailed` | Redis could not be reached or returned an error |
|
|
101
|
+
|
|
102
|
+
If Redis goes down, you decide whether to let requests through:
|
|
103
|
+
|
|
104
|
+
```python
|
|
105
|
+
from flowix import BackendFailed
|
|
106
|
+
|
|
107
|
+
try:
|
|
108
|
+
allowed = run_limiter("user:1", limiter, client)["allowed"]
|
|
109
|
+
except BackendFailed:
|
|
110
|
+
allowed = True # or False to reject
|
|
111
|
+
```
|
|
112
|
+
|
|
113
|
+
## Limitations
|
|
114
|
+
|
|
115
|
+
- Synchronous `redis.Redis` clients only; async clients are not supported yet.
|
|
116
|
+
- Redis Cluster clients (`RedisCluster`) are not supported yet.
|
|
117
|
+
|
|
118
|
+
## Running the tests
|
|
119
|
+
|
|
120
|
+
The tests need a running Redis. They use database 15 on `localhost:6379`, and delete
|
|
121
|
+
only the keys they create. Set `FLOWIX_TEST_REDIS_URL` to use a different one.
|
|
122
|
+
|
|
123
|
+
```bash
|
|
124
|
+
uv run pytest
|
|
125
|
+
```
|
|
126
|
+
|
|
127
|
+
## License
|
|
128
|
+
|
|
129
|
+
MIT
|
flowix-0.1.0/README.md
ADDED
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
# flowix
|
|
2
|
+
|
|
3
|
+
Distributed, atomic rate limiting for Python, powered by Redis.
|
|
4
|
+
|
|
5
|
+
- **Distributed:** every app server using the same Redis shares the same limits.
|
|
6
|
+
- **Atomic:** each check is a single Lua script, so simultaneous requests can't slip past a limit.
|
|
7
|
+
- **One clock:** timing comes from the Redis server, not from your app servers.
|
|
8
|
+
|
|
9
|
+
## Install
|
|
10
|
+
|
|
11
|
+
```bash
|
|
12
|
+
pip install flowix
|
|
13
|
+
```
|
|
14
|
+
|
|
15
|
+
Requires Python 3.10+ and Redis 5+.
|
|
16
|
+
|
|
17
|
+
## Quick start
|
|
18
|
+
|
|
19
|
+
```python
|
|
20
|
+
from redis import Redis
|
|
21
|
+
from flowix import create_limiter, run_limiter
|
|
22
|
+
|
|
23
|
+
client = Redis.from_url("redis://localhost:6379")
|
|
24
|
+
limiter = create_limiter("token", capacity=3, refill_rate=1, refill_interval=10)
|
|
25
|
+
|
|
26
|
+
result = run_limiter("user:1", limiter, client)
|
|
27
|
+
|
|
28
|
+
if result["allowed"]:
|
|
29
|
+
print("go ahead")
|
|
30
|
+
else:
|
|
31
|
+
print(f"try again in {result['retry_after']} seconds")
|
|
32
|
+
```
|
|
33
|
+
|
|
34
|
+
`run_limiter` returns a dict:
|
|
35
|
+
|
|
36
|
+
| Key | Type | Meaning |
|
|
37
|
+
|---|---|---|
|
|
38
|
+
| `allowed` | `bool` | Whether the request may proceed |
|
|
39
|
+
| `retry_after` | `int` | Whole seconds until a request can be allowed, `0` when allowed |
|
|
40
|
+
|
|
41
|
+
## Algorithms
|
|
42
|
+
|
|
43
|
+
### Token bucket
|
|
44
|
+
|
|
45
|
+
```python
|
|
46
|
+
create_limiter("token", capacity=10, refill_rate=5, refill_interval=60)
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
Allows bursts of up to `capacity` requests, then adds `refill_rate` tokens every
|
|
50
|
+
`refill_interval` seconds. Each request uses one token.
|
|
51
|
+
|
|
52
|
+
### Leaky bucket
|
|
53
|
+
|
|
54
|
+
```python
|
|
55
|
+
create_limiter("leaky", capacity=10, leak_rate=2)
|
|
56
|
+
```
|
|
57
|
+
|
|
58
|
+
Each request fills the bucket by one, and it drains continuously at `leak_rate`
|
|
59
|
+
requests per second. Requests are rejected while the bucket is full. Requests are
|
|
60
|
+
not queued or delayed.
|
|
61
|
+
|
|
62
|
+
## Choosing keys
|
|
63
|
+
|
|
64
|
+
A key identifies what is being limited, such as a user or an IP address. Limiters
|
|
65
|
+
using the same algorithm and the same key share one bucket, so give each limit its
|
|
66
|
+
own key:
|
|
67
|
+
|
|
68
|
+
```python
|
|
69
|
+
run_limiter("login:user:1", login_limiter, client)
|
|
70
|
+
run_limiter("search:user:1", search_limiter, client)
|
|
71
|
+
```
|
|
72
|
+
|
|
73
|
+
flowix stores its data in Redis under `flowix:`.
|
|
74
|
+
|
|
75
|
+
## Errors
|
|
76
|
+
|
|
77
|
+
Every exception inherits from `FlowixError`.
|
|
78
|
+
|
|
79
|
+
| Exception | Raised when |
|
|
80
|
+
|---|---|
|
|
81
|
+
| `InvalidParameterType` | A parameter has the wrong type |
|
|
82
|
+
| `InvalidParameterValue` | A number is zero or negative |
|
|
83
|
+
| `IncorrectParameters` | Parameters are missing or not accepted by the algorithm |
|
|
84
|
+
| `UnsupportedAlgorithm` | The algorithm does not exist |
|
|
85
|
+
| `BackendFailed` | Redis could not be reached or returned an error |
|
|
86
|
+
|
|
87
|
+
If Redis goes down, you decide whether to let requests through:
|
|
88
|
+
|
|
89
|
+
```python
|
|
90
|
+
from flowix import BackendFailed
|
|
91
|
+
|
|
92
|
+
try:
|
|
93
|
+
allowed = run_limiter("user:1", limiter, client)["allowed"]
|
|
94
|
+
except BackendFailed:
|
|
95
|
+
allowed = True # or False to reject
|
|
96
|
+
```
|
|
97
|
+
|
|
98
|
+
## Limitations
|
|
99
|
+
|
|
100
|
+
- Synchronous `redis.Redis` clients only; async clients are not supported yet.
|
|
101
|
+
- Redis Cluster clients (`RedisCluster`) are not supported yet.
|
|
102
|
+
|
|
103
|
+
## Running the tests
|
|
104
|
+
|
|
105
|
+
The tests need a running Redis. They use database 15 on `localhost:6379`, and delete
|
|
106
|
+
only the keys they create. Set `FLOWIX_TEST_REDIS_URL` to use a different one.
|
|
107
|
+
|
|
108
|
+
```bash
|
|
109
|
+
uv run pytest
|
|
110
|
+
```
|
|
111
|
+
|
|
112
|
+
## License
|
|
113
|
+
|
|
114
|
+
MIT
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
[project]
|
|
2
|
+
name = "flowix"
|
|
3
|
+
version = "0.1.0"
|
|
4
|
+
description = "Distributed, atomic rate limiting for Python, powered by Redis"
|
|
5
|
+
readme = "README.md"
|
|
6
|
+
license = "MIT"
|
|
7
|
+
license-files = ["LICENSE"]
|
|
8
|
+
requires-python = ">=3.10"
|
|
9
|
+
dependencies = ["redis>=4.3.4"]
|
|
10
|
+
keywords = ["rate-limiting", "rate-limiter", "redis", "throttling"]
|
|
11
|
+
classifiers = [
|
|
12
|
+
"Development Status :: 3 - Alpha",
|
|
13
|
+
"Intended Audience :: Developers",
|
|
14
|
+
"Programming Language :: Python :: 3",
|
|
15
|
+
"Typing :: Typed",
|
|
16
|
+
]
|
|
17
|
+
|
|
18
|
+
[dependency-groups]
|
|
19
|
+
dev = ["pytest>=8"]
|
|
20
|
+
|
|
21
|
+
[build-system]
|
|
22
|
+
requires = ["hatchling"]
|
|
23
|
+
build-backend = "hatchling.build"
|
|
24
|
+
|
|
25
|
+
[tool.hatch.build.targets.sdist]
|
|
26
|
+
include = ["/src", "/tests", "/README.md", "/LICENSE"]
|
|
27
|
+
|
|
28
|
+
[tool.pytest.ini_options]
|
|
29
|
+
testpaths = ["tests"]
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
from .engine import create_limiter, run_limiter
|
|
2
|
+
from .exceptions import (
|
|
3
|
+
BackendFailed,
|
|
4
|
+
FlowixError,
|
|
5
|
+
IncorrectParameters,
|
|
6
|
+
InvalidParameterType,
|
|
7
|
+
InvalidParameterValue,
|
|
8
|
+
RequestDisallowed,
|
|
9
|
+
UnsupportedAlgorithm,
|
|
10
|
+
)
|
|
11
|
+
from .interfaces import LimitResult
|
|
12
|
+
from .limiter import LeakyBucketLimiter, TokenBucketLimiter
|
|
13
|
+
|
|
14
|
+
__all__ = [
|
|
15
|
+
"create_limiter",
|
|
16
|
+
"run_limiter",
|
|
17
|
+
"LeakyBucketLimiter",
|
|
18
|
+
"TokenBucketLimiter",
|
|
19
|
+
"LimitResult",
|
|
20
|
+
"FlowixError",
|
|
21
|
+
"InvalidParameterType",
|
|
22
|
+
"InvalidParameterValue",
|
|
23
|
+
"IncorrectParameters",
|
|
24
|
+
"UnsupportedAlgorithm",
|
|
25
|
+
"BackendFailed",
|
|
26
|
+
"RequestDisallowed",
|
|
27
|
+
]
|
|
File without changes
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
leaky_bucket_script= """
|
|
2
|
+
local key = KEYS[1]
|
|
3
|
+
local capacity = tonumber(ARGV[1])
|
|
4
|
+
local leak_rate = tonumber(ARGV[2])
|
|
5
|
+
|
|
6
|
+
local t = redis.call('TIME')
|
|
7
|
+
local now = tonumber(t[1]) + tonumber(t[2]) / 1e6
|
|
8
|
+
|
|
9
|
+
local data = redis.call('HGETALL', key)
|
|
10
|
+
local level = 0
|
|
11
|
+
local last_leak = now
|
|
12
|
+
|
|
13
|
+
if #data > 0 then
|
|
14
|
+
for i = 1, #data, 2 do
|
|
15
|
+
if data[i] == 'level' then
|
|
16
|
+
level = tonumber(data[i+1])
|
|
17
|
+
elseif data[i] == 'last_leak' then
|
|
18
|
+
last_leak = tonumber(data[i+1])
|
|
19
|
+
end
|
|
20
|
+
end
|
|
21
|
+
end
|
|
22
|
+
|
|
23
|
+
if now < last_leak then
|
|
24
|
+
-- clock moved backwards (e.g. failover): restart from now. Saved here
|
|
25
|
+
-- because a blocked request returns below without writing anything
|
|
26
|
+
last_leak = now
|
|
27
|
+
redis.call('HSET', key, 'last_leak', last_leak)
|
|
28
|
+
end
|
|
29
|
+
|
|
30
|
+
local elapsed = now - last_leak
|
|
31
|
+
level = math.max(0, level - elapsed * leak_rate)
|
|
32
|
+
|
|
33
|
+
if level + 1 > capacity then
|
|
34
|
+
-- seconds; rounded up so clients never retry too early
|
|
35
|
+
return {0, math.ceil((level + 1 - capacity) / leak_rate)}
|
|
36
|
+
end
|
|
37
|
+
|
|
38
|
+
level = level + 1
|
|
39
|
+
local ttl = math.ceil(capacity / leak_rate) + 1
|
|
40
|
+
|
|
41
|
+
redis.call('HSET', key, 'level', level, 'last_leak', now)
|
|
42
|
+
redis.call('EXPIRE', key, ttl)
|
|
43
|
+
|
|
44
|
+
return {1, 0}
|
|
45
|
+
"""
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
token_bucket_script = """
|
|
2
|
+
local key = KEYS[1]
|
|
3
|
+
local capacity = tonumber(ARGV[1])
|
|
4
|
+
local refill_rate = tonumber(ARGV[2])
|
|
5
|
+
local refill_interval = tonumber(ARGV[3])
|
|
6
|
+
|
|
7
|
+
local t = redis.call('TIME')
|
|
8
|
+
local now = tonumber(t[1]) + tonumber(t[2]) / 1e6
|
|
9
|
+
|
|
10
|
+
local bucket = redis.call('HMGET', key, 'tokens', 'last_refill')
|
|
11
|
+
local tokens = tonumber(bucket[1])
|
|
12
|
+
local last_refill = tonumber(bucket[2])
|
|
13
|
+
|
|
14
|
+
if tokens == nil then
|
|
15
|
+
tokens = capacity
|
|
16
|
+
last_refill = now
|
|
17
|
+
end
|
|
18
|
+
|
|
19
|
+
-- clock moved backwards (e.g. failover): restart the interval from now
|
|
20
|
+
if last_refill > now then
|
|
21
|
+
last_refill = now
|
|
22
|
+
end
|
|
23
|
+
|
|
24
|
+
local time_passed = now - last_refill
|
|
25
|
+
local refills = math.floor(time_passed / refill_interval)
|
|
26
|
+
|
|
27
|
+
if refills > 0 then
|
|
28
|
+
tokens = math.min(capacity, tokens + (refills * refill_rate))
|
|
29
|
+
last_refill = last_refill + (refills * refill_interval)
|
|
30
|
+
end
|
|
31
|
+
|
|
32
|
+
local allowed = 0
|
|
33
|
+
local retry_after = 0
|
|
34
|
+
|
|
35
|
+
if tokens >= 1 then
|
|
36
|
+
tokens = tokens - 1
|
|
37
|
+
allowed = 1
|
|
38
|
+
else
|
|
39
|
+
-- seconds until the bucket holds a full token again; a refill_rate below 1
|
|
40
|
+
-- can need several intervals. Rounded up: Redis truncates decimals on return
|
|
41
|
+
local refills_needed = math.ceil((1 - tokens) / refill_rate)
|
|
42
|
+
retry_after = math.ceil(last_refill + (refills_needed * refill_interval) - now)
|
|
43
|
+
end
|
|
44
|
+
|
|
45
|
+
redis.call('HSET', key, 'tokens', tokens, 'last_refill', last_refill)
|
|
46
|
+
|
|
47
|
+
local ttl = math.ceil(capacity / refill_rate * refill_interval) + 10
|
|
48
|
+
redis.call('EXPIRE',key,ttl)
|
|
49
|
+
|
|
50
|
+
return {allowed, retry_after}
|
|
51
|
+
"""
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
from typing import Any, Literal, overload
|
|
2
|
+
from redis import Redis
|
|
3
|
+
from redis.exceptions import RedisError
|
|
4
|
+
from .algorithm_lua_scripts.leaky_bucket import leaky_bucket_script
|
|
5
|
+
from .algorithm_lua_scripts.token_bucket import token_bucket_script
|
|
6
|
+
from .exceptions import (
|
|
7
|
+
BackendFailed,
|
|
8
|
+
IncorrectParameters,
|
|
9
|
+
InvalidParameterType,
|
|
10
|
+
UnsupportedAlgorithm,
|
|
11
|
+
)
|
|
12
|
+
from .interfaces import AlgoType, LimitResult
|
|
13
|
+
from .limiter import LeakyBucketLimiter, TokenBucketLimiter
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
@overload
|
|
17
|
+
def create_limiter(
|
|
18
|
+
algo_type: Literal["leaky"],
|
|
19
|
+
*,
|
|
20
|
+
capacity: int,
|
|
21
|
+
leak_rate: float
|
|
22
|
+
) -> LeakyBucketLimiter: ...
|
|
23
|
+
|
|
24
|
+
@overload
|
|
25
|
+
def create_limiter(
|
|
26
|
+
algo_type: Literal["token"],
|
|
27
|
+
*,
|
|
28
|
+
capacity: int,
|
|
29
|
+
refill_rate: float,
|
|
30
|
+
refill_interval: float
|
|
31
|
+
) -> TokenBucketLimiter: ...
|
|
32
|
+
|
|
33
|
+
def create_limiter(algo_type: str, **kwargs: Any) -> AlgoType:
|
|
34
|
+
if algo_type == "leaky":
|
|
35
|
+
leaky_params = {"capacity","leak_rate"}
|
|
36
|
+
if not kwargs.keys() == leaky_params:
|
|
37
|
+
raise IncorrectParameters(f"leaky takes exactly {sorted(leaky_params)}, got {sorted(kwargs)}")
|
|
38
|
+
return LeakyBucketLimiter(**kwargs)
|
|
39
|
+
|
|
40
|
+
elif algo_type == "token":
|
|
41
|
+
token_params = {"capacity","refill_rate","refill_interval"}
|
|
42
|
+
if not kwargs.keys() == token_params:
|
|
43
|
+
raise IncorrectParameters(f"token takes exactly {sorted(token_params)}, got {sorted(kwargs)}")
|
|
44
|
+
return TokenBucketLimiter(**kwargs)
|
|
45
|
+
|
|
46
|
+
raise UnsupportedAlgorithm(f"Unsupported algorithm: {algo_type}")
|
|
47
|
+
|
|
48
|
+
def run_limiter(key: str, limiter: AlgoType, client: Redis) -> LimitResult:
|
|
49
|
+
if not isinstance(limiter, AlgoType):
|
|
50
|
+
raise InvalidParameterType("limiter must be an algotype")
|
|
51
|
+
if not isinstance(key,str):
|
|
52
|
+
raise InvalidParameterType("key must be a string")
|
|
53
|
+
if not isinstance(client,Redis):
|
|
54
|
+
raise InvalidParameterType("client must be a redis.Redis instance")
|
|
55
|
+
try:
|
|
56
|
+
if isinstance(limiter, TokenBucketLimiter):
|
|
57
|
+
# order must match ARGV[1..3] in the lua script
|
|
58
|
+
args = [
|
|
59
|
+
limiter.capacity,
|
|
60
|
+
limiter.refill_rate,
|
|
61
|
+
limiter.refill_interval,
|
|
62
|
+
]
|
|
63
|
+
token_bucket = client.register_script(token_bucket_script)
|
|
64
|
+
allowed, retry_after = token_bucket(keys=[f"flowix:token:{key}"],args=args)
|
|
65
|
+
else:
|
|
66
|
+
# order must match ARGV[1..2] in the lua script
|
|
67
|
+
args = [limiter.capacity, limiter.leak_rate]
|
|
68
|
+
leaky_bucket = client.register_script(leaky_bucket_script)
|
|
69
|
+
allowed, retry_after = leaky_bucket(keys=[f"flowix:leaky:{key}"],args=args)
|
|
70
|
+
except RedisError as exc:
|
|
71
|
+
raise BackendFailed(f"Redis call failed: {exc}") from exc
|
|
72
|
+
|
|
73
|
+
return {"allowed": bool(allowed), "retry_after": retry_after}
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
class FlowixError(Exception):
|
|
2
|
+
"""Base class for every flowix exception"""
|
|
3
|
+
pass
|
|
4
|
+
|
|
5
|
+
class InvalidParameterType(FlowixError, TypeError):
|
|
6
|
+
"""A parameter has the wrong type"""
|
|
7
|
+
pass
|
|
8
|
+
|
|
9
|
+
class InvalidParameterValue(FlowixError, ValueError):
|
|
10
|
+
"""A parameter has the right type but a value that is not allowed"""
|
|
11
|
+
pass
|
|
12
|
+
|
|
13
|
+
class IncorrectParameters(FlowixError, ValueError):
|
|
14
|
+
"""Parameters are missing, or not accepted by the chosen algorithm"""
|
|
15
|
+
pass
|
|
16
|
+
|
|
17
|
+
class UnsupportedAlgorithm(FlowixError, ValueError):
|
|
18
|
+
"""The algorithm does not exist"""
|
|
19
|
+
pass
|
|
20
|
+
|
|
21
|
+
class BackendFailed(FlowixError):
|
|
22
|
+
"""Redis could not be reached or returned an error"""
|
|
23
|
+
pass
|
|
24
|
+
|
|
25
|
+
class RequestDisallowed(FlowixError):
|
|
26
|
+
"""Request was not allowed, It has been limited"""
|
|
27
|
+
pass
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
from .exceptions import InvalidParameterType, InvalidParameterValue
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
class LeakyBucketLimiter:
|
|
5
|
+
def __init__(self, capacity: int, leak_rate: float) -> None:
|
|
6
|
+
if not isinstance(capacity,int) or isinstance(capacity,bool):
|
|
7
|
+
raise InvalidParameterType("capacity must be an integer")
|
|
8
|
+
if not isinstance(leak_rate,(int,float)):
|
|
9
|
+
raise InvalidParameterType("leak_rate must be a number")
|
|
10
|
+
if capacity <= 0:
|
|
11
|
+
raise InvalidParameterValue('capacity must be positive')
|
|
12
|
+
if leak_rate <= 0:
|
|
13
|
+
raise InvalidParameterValue("leak_rate must be positive")
|
|
14
|
+
self.capacity = capacity
|
|
15
|
+
self.leak_rate = leak_rate
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
class TokenBucketLimiter:
|
|
19
|
+
def __init__(
|
|
20
|
+
self,
|
|
21
|
+
capacity: int,
|
|
22
|
+
refill_rate: float,
|
|
23
|
+
refill_interval: float
|
|
24
|
+
) -> None:
|
|
25
|
+
if not isinstance(refill_rate,(int,float)):
|
|
26
|
+
raise InvalidParameterType("refill_rate must be a number")
|
|
27
|
+
if not isinstance(refill_interval,(int,float)):
|
|
28
|
+
raise InvalidParameterType("refill_interval must be a number")
|
|
29
|
+
if not isinstance(capacity,int) or isinstance(capacity,bool):
|
|
30
|
+
raise InvalidParameterType("capacity must be an integer")
|
|
31
|
+
if capacity <= 0:
|
|
32
|
+
raise InvalidParameterValue("capacity must be positive")
|
|
33
|
+
if refill_rate <= 0:
|
|
34
|
+
raise InvalidParameterValue("refill_rate must be positive")
|
|
35
|
+
if refill_interval <= 0:
|
|
36
|
+
raise InvalidParameterValue("refill_interval must be positive")
|
|
37
|
+
|
|
38
|
+
self.capacity = capacity
|
|
39
|
+
self.refill_rate = refill_rate
|
|
40
|
+
self.refill_interval = refill_interval
|
|
File without changes
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import os
|
|
2
|
+
import uuid
|
|
3
|
+
|
|
4
|
+
import pytest
|
|
5
|
+
from redis import Redis
|
|
6
|
+
|
|
7
|
+
URL = os.environ.get("FLOWIX_TEST_REDIS_URL", "redis://localhost:6379/15")
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
@pytest.fixture(params=[True, False], ids=["str-client", "bytes-client"])
|
|
11
|
+
def client(request):
|
|
12
|
+
client = Redis.from_url(URL, decode_responses=request.param)
|
|
13
|
+
yield client
|
|
14
|
+
client.close()
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
@pytest.fixture
|
|
18
|
+
def key():
|
|
19
|
+
"""A key no other test uses; everything stored under it is deleted afterwards."""
|
|
20
|
+
key = f"flowixtest-{uuid.uuid4().hex}"
|
|
21
|
+
yield key
|
|
22
|
+
client = Redis.from_url(URL)
|
|
23
|
+
for name in client.scan_iter(f"*{key}*"):
|
|
24
|
+
client.delete(name)
|
|
25
|
+
client.close()
|
|
@@ -0,0 +1,127 @@
|
|
|
1
|
+
import math
|
|
2
|
+
import time
|
|
3
|
+
from concurrent.futures import ThreadPoolExecutor
|
|
4
|
+
|
|
5
|
+
import pytest
|
|
6
|
+
|
|
7
|
+
from flowix import create_limiter, run_limiter
|
|
8
|
+
from flowix.algorithm_lua_scripts.leaky_bucket import leaky_bucket_script
|
|
9
|
+
from flowix.algorithm_lua_scripts.token_bucket import token_bucket_script
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def allowed(key, limiter, client, times):
|
|
13
|
+
return [run_limiter(key, limiter, client)["allowed"] for _ in range(times)]
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
@pytest.mark.parametrize("algo, params", [
|
|
17
|
+
("token", {"capacity": 3, "refill_rate": 1, "refill_interval": 1}),
|
|
18
|
+
("token", {"capacity": 1, "refill_rate": 0.5, "refill_interval": 1}),
|
|
19
|
+
("leaky", {"capacity": 3, "leak_rate": 1}),
|
|
20
|
+
("leaky", {"capacity": 1, "leak_rate": 0.5}),
|
|
21
|
+
])
|
|
22
|
+
def test_blocks_at_capacity_then_allows_after_retry_after(client, key, algo, params):
|
|
23
|
+
limiter = create_limiter(algo, **params)
|
|
24
|
+
assert allowed(key, limiter, client, params["capacity"]) == [True] * params["capacity"]
|
|
25
|
+
|
|
26
|
+
blocked = run_limiter(key, limiter, client)
|
|
27
|
+
assert blocked["allowed"] is False
|
|
28
|
+
assert blocked["retry_after"] >= 1
|
|
29
|
+
|
|
30
|
+
time.sleep(blocked["retry_after"])
|
|
31
|
+
assert run_limiter(key, limiter, client) == {"allowed": True, "retry_after": 0}
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
@pytest.mark.parametrize("algo, params", [
|
|
35
|
+
("token", {"capacity": 50, "refill_rate": 1, "refill_interval": 3600}),
|
|
36
|
+
("leaky", {"capacity": 50, "leak_rate": 0.0001}),
|
|
37
|
+
])
|
|
38
|
+
def test_concurrent_requests_never_exceed_capacity(client, key, algo, params):
|
|
39
|
+
limiter = create_limiter(algo, **params)
|
|
40
|
+
with ThreadPoolExecutor(20) as pool:
|
|
41
|
+
results = list(pool.map(lambda _: run_limiter(key, limiter, client)["allowed"], range(200)))
|
|
42
|
+
assert sum(results) == 50
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
@pytest.mark.parametrize("algo, params, drain_time", [
|
|
46
|
+
("token", {"capacity": 10, "refill_rate": 2, "refill_interval": 6}, 30),
|
|
47
|
+
("leaky", {"capacity": 10, "leak_rate": 0.5}, 20),
|
|
48
|
+
])
|
|
49
|
+
def test_bucket_outlives_its_full_recovery(client, key, algo, params, drain_time):
|
|
50
|
+
# expiring any sooner would hand out a full bucket early
|
|
51
|
+
run_limiter(key, create_limiter(algo, **params), client)
|
|
52
|
+
assert client.ttl(f"flowix:{algo}:{key}") >= drain_time
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def test_idle_bucket_expires(client, key):
|
|
56
|
+
run_limiter(key, create_limiter("leaky", capacity=1, leak_rate=1), client)
|
|
57
|
+
time.sleep(2.5)
|
|
58
|
+
assert not client.exists(f"flowix:leaky:{key}")
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def test_algorithms_do_not_share_a_bucket(client, key):
|
|
62
|
+
token = create_limiter("token", capacity=2, refill_rate=1, refill_interval=60)
|
|
63
|
+
leaky = create_limiter("leaky", capacity=2, leak_rate=5)
|
|
64
|
+
allowed(key, token, client, 2)
|
|
65
|
+
assert run_limiter(key, leaky, client)["allowed"]
|
|
66
|
+
time.sleep(2.5) # longer than the leaky bucket's ttl
|
|
67
|
+
assert not run_limiter(key, token, client)["allowed"]
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
@pytest.mark.parametrize("prefix", ["token", "leaky"])
|
|
71
|
+
def test_does_not_touch_the_apps_own_keys(client, key, prefix):
|
|
72
|
+
client.hset(f"{prefix}:{key}", mapping={"user": "42"})
|
|
73
|
+
run_limiter(key, create_limiter("token", capacity=2, refill_rate=1, refill_interval=1), client)
|
|
74
|
+
run_limiter(key, create_limiter("leaky", capacity=2, leak_rate=1), client)
|
|
75
|
+
assert client.hlen(f"{prefix}:{key}") == 1
|
|
76
|
+
assert client.ttl(f"{prefix}:{key}") == -1
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
# The scripts read Redis' clock, so these run a copy that takes the time as its
|
|
80
|
+
# last argument instead.
|
|
81
|
+
|
|
82
|
+
NOW = "local now = tonumber(t[1]) + tonumber(t[2]) / 1e6"
|
|
83
|
+
T = 1_700_000_000.25
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def with_fake_clock(client, script, key, *args):
|
|
87
|
+
assert script.count(NOW) == 1
|
|
88
|
+
fake = client.register_script(script.replace(NOW, f"local now = tonumber(ARGV[{len(args) + 1}])"))
|
|
89
|
+
return lambda now: fake(keys=[f"flowix:{key}"], args=[*args, now])
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def test_token_clock_moving_backwards(client, key):
|
|
93
|
+
run = with_fake_clock(client, token_bucket_script, key, 3, 1, 60)
|
|
94
|
+
for _ in range(3):
|
|
95
|
+
run(T)
|
|
96
|
+
assert run(T - 10) == [0, 60]
|
|
97
|
+
assert run(T + 49) == [0, 1]
|
|
98
|
+
assert run(T + 50) == [1, 0]
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def test_leaky_clock_moving_backwards(client, key):
|
|
102
|
+
run = with_fake_clock(client, leaky_bucket_script, key, 3, 1)
|
|
103
|
+
for _ in range(3):
|
|
104
|
+
run(T)
|
|
105
|
+
assert run(T - 10) == [0, 1]
|
|
106
|
+
assert run(T - 9) == [1, 0]
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def test_token_retry_after_counts_time_already_passed(client, key):
|
|
110
|
+
run = with_fake_clock(client, token_bucket_script, key, 3, 1, 60)
|
|
111
|
+
for _ in range(3):
|
|
112
|
+
run(T)
|
|
113
|
+
assert run(T + 20) == [0, 40]
|
|
114
|
+
assert run(T + 59.5) == [0, 1]
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
def test_leaky_allows_a_steady_stream_at_the_leak_rate(client, key):
|
|
118
|
+
run = with_fake_clock(client, leaky_bucket_script, key, 3, 1)
|
|
119
|
+
for _ in range(3):
|
|
120
|
+
run(T)
|
|
121
|
+
assert all(run(T + second) == [1, 0] for second in range(1, 51))
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
def test_leaky_retry_after_rounds_up(client, key):
|
|
125
|
+
run = with_fake_clock(client, leaky_bucket_script, key, 1, 0.3)
|
|
126
|
+
run(T)
|
|
127
|
+
assert run(T) == [0, math.ceil(1 / 0.3)]
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
import pytest
|
|
2
|
+
import redis.asyncio
|
|
3
|
+
from redis import Redis
|
|
4
|
+
|
|
5
|
+
import flowix
|
|
6
|
+
from flowix import create_limiter, run_limiter
|
|
7
|
+
|
|
8
|
+
LEAKY = {"capacity": 2, "leak_rate": 1}
|
|
9
|
+
TOKEN = {"capacity": 2, "refill_rate": 1, "refill_interval": 1}
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def test_everything_in_all_is_exported():
|
|
13
|
+
for name in flowix.__all__:
|
|
14
|
+
assert hasattr(flowix, name)
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def test_creates_the_right_limiter():
|
|
18
|
+
assert isinstance(create_limiter("leaky", **LEAKY), flowix.LeakyBucketLimiter)
|
|
19
|
+
assert isinstance(create_limiter("token", **TOKEN), flowix.TokenBucketLimiter)
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def test_unsupported_algorithm():
|
|
23
|
+
with pytest.raises(flowix.UnsupportedAlgorithm):
|
|
24
|
+
create_limiter("nope")
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
@pytest.mark.parametrize("algo, params", [
|
|
28
|
+
("leaky", {"capacity": 2}),
|
|
29
|
+
("leaky", {**LEAKY, "refill_rate": 1}),
|
|
30
|
+
("token", {"capacity": 2, "leak_rate": 1}),
|
|
31
|
+
])
|
|
32
|
+
def test_missing_or_extra_parameters(algo, params):
|
|
33
|
+
with pytest.raises(flowix.IncorrectParameters):
|
|
34
|
+
create_limiter(algo, **params)
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
@pytest.mark.parametrize("algo, params", [("leaky", LEAKY), ("token", TOKEN)])
|
|
38
|
+
def test_wrong_types_and_non_positive_values(algo, params):
|
|
39
|
+
for name in params:
|
|
40
|
+
with pytest.raises(flowix.InvalidParameterType):
|
|
41
|
+
create_limiter(algo, **{**params, name: "1"})
|
|
42
|
+
for value in (0, -1):
|
|
43
|
+
with pytest.raises(flowix.InvalidParameterValue):
|
|
44
|
+
create_limiter(algo, **{**params, name: value})
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
@pytest.mark.parametrize("capacity", [True, 1.5])
|
|
48
|
+
def test_capacity_must_be_an_integer(capacity):
|
|
49
|
+
with pytest.raises(flowix.InvalidParameterType):
|
|
50
|
+
create_limiter("leaky", capacity=capacity, leak_rate=1)
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
@pytest.mark.parametrize("error, builtin", [
|
|
54
|
+
(flowix.InvalidParameterType, TypeError),
|
|
55
|
+
(flowix.InvalidParameterValue, ValueError),
|
|
56
|
+
(flowix.IncorrectParameters, ValueError),
|
|
57
|
+
(flowix.UnsupportedAlgorithm, ValueError),
|
|
58
|
+
])
|
|
59
|
+
def test_exceptions_are_also_builtin_ones(error, builtin):
|
|
60
|
+
assert issubclass(error, flowix.FlowixError)
|
|
61
|
+
assert issubclass(error, builtin)
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def test_run_limiter_rejects_wrong_types():
|
|
65
|
+
limiter = create_limiter("leaky", **LEAKY)
|
|
66
|
+
with pytest.raises(flowix.InvalidParameterType):
|
|
67
|
+
run_limiter("a", object(), Redis())
|
|
68
|
+
with pytest.raises(flowix.InvalidParameterType):
|
|
69
|
+
run_limiter(1, limiter, Redis())
|
|
70
|
+
for client in (None, redis.asyncio.Redis()):
|
|
71
|
+
with pytest.raises(flowix.InvalidParameterType):
|
|
72
|
+
run_limiter("a", limiter, client)
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def test_redis_down_raises_backend_failed():
|
|
76
|
+
limiter = create_limiter("leaky", **LEAKY)
|
|
77
|
+
with pytest.raises(flowix.BackendFailed) as error:
|
|
78
|
+
run_limiter("a", limiter, Redis(port=1))
|
|
79
|
+
assert isinstance(error.value.__cause__, redis.exceptions.RedisError)
|