flowix 0.1.0__py3-none-any.whl

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/__init__.py ADDED
@@ -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
+ """
flowix/engine.py ADDED
@@ -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}
flowix/exceptions.py ADDED
@@ -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
flowix/interfaces.py ADDED
@@ -0,0 +1,9 @@
1
+ from typing import TypedDict
2
+ from .limiter import LeakyBucketLimiter, TokenBucketLimiter
3
+
4
+ AlgoType = LeakyBucketLimiter | TokenBucketLimiter
5
+
6
+
7
+ class LimitResult(TypedDict):
8
+ allowed: bool
9
+ retry_after: int # seconds, 0 when allowed
flowix/limiter.py ADDED
@@ -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
flowix/py.typed ADDED
File without changes
@@ -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
@@ -0,0 +1,13 @@
1
+ flowix/__init__.py,sha256=tBFCBPX0vARbisvLAlhT0kZ_HXjQ9I2wYRfZUaHksHk,639
2
+ flowix/engine.py,sha256=__gwEUc6zr1rAMJBXLRGLJWzC2SBFfkTjsAe88PSvFw,2758
3
+ flowix/exceptions.py,sha256=BjX45XxOOJV43Rd1dW5c1hh9m8F3RgopqLRo8aK2Ayo,770
4
+ flowix/interfaces.py,sha256=UXCheRhFukAl1Xt6RSJbBLWe6LuvMaDfaQqeXzp5anc,239
5
+ flowix/limiter.py,sha256=fCMDVUsdL5s5RFwPOwdbWUY880x-N5j6n6TI2TbRiqM,1655
6
+ flowix/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
7
+ flowix/algorithm_lua_scripts/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
8
+ flowix/algorithm_lua_scripts/leaky_bucket.py,sha256=bChrx6t8sSqoMyrmQxkkW2e8eKM0kvDA9Lwocz08RDs,1187
9
+ flowix/algorithm_lua_scripts/token_bucket.py,sha256=WDbSDozX80PgSCKjsgxxKJ1iIyuHURNuTvPh13yUrkY,1453
10
+ flowix-0.1.0.dist-info/METADATA,sha256=I1O2sG8z6A0JJzH6pUmQQYxYZd2dWIcqkSFuYtnQYlk,3460
11
+ flowix-0.1.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
12
+ flowix-0.1.0.dist-info/licenses/LICENSE,sha256=84XNR34eHGVPNMSaSlqhcQuvKL85-w2KItI0-H1c990,1063
13
+ flowix-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.33.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -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.