pycurb 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.
Files changed (51) hide show
  1. pycurb-0.1.0/LICENSE +201 -0
  2. pycurb-0.1.0/PKG-INFO +256 -0
  3. pycurb-0.1.0/README.md +213 -0
  4. pycurb-0.1.0/pyproject.toml +87 -0
  5. pycurb-0.1.0/setup.cfg +4 -0
  6. pycurb-0.1.0/src/pycurb/__init__.py +0 -0
  7. pycurb-0.1.0/src/pycurb/adapters/django/__init__.py +11 -0
  8. pycurb-0.1.0/src/pycurb/adapters/django/decorators.py +77 -0
  9. pycurb-0.1.0/src/pycurb/adapters/django/extractors.py +25 -0
  10. pycurb-0.1.0/src/pycurb/adapters/django/middleware.py +46 -0
  11. pycurb-0.1.0/src/pycurb/adapters/fastapi/__init__.py +17 -0
  12. pycurb-0.1.0/src/pycurb/adapters/fastapi/dependencies.py +30 -0
  13. pycurb-0.1.0/src/pycurb/adapters/fastapi/extractors.py +24 -0
  14. pycurb-0.1.0/src/pycurb/adapters/fastapi/middleware.py +53 -0
  15. pycurb-0.1.0/src/pycurb/adapters/flask/__init__.py +17 -0
  16. pycurb-0.1.0/src/pycurb/adapters/flask/decorators.py +44 -0
  17. pycurb-0.1.0/src/pycurb/adapters/flask/extractors.py +35 -0
  18. pycurb-0.1.0/src/pycurb/adapters/flask/middleware.py +54 -0
  19. pycurb-0.1.0/src/pycurb/core/__init__.py +24 -0
  20. pycurb-0.1.0/src/pycurb/core/algorithms/__init__.py +12 -0
  21. pycurb-0.1.0/src/pycurb/core/algorithms/base.py +21 -0
  22. pycurb-0.1.0/src/pycurb/core/algorithms/base_async.py +23 -0
  23. pycurb-0.1.0/src/pycurb/core/algorithms/fixed_window.py +26 -0
  24. pycurb-0.1.0/src/pycurb/core/algorithms/fixed_window_async.py +28 -0
  25. pycurb-0.1.0/src/pycurb/core/algorithms/gcra.py +38 -0
  26. pycurb-0.1.0/src/pycurb/core/algorithms/gcra_async.py +40 -0
  27. pycurb-0.1.0/src/pycurb/core/algorithms/leaky_bucket.py +40 -0
  28. pycurb-0.1.0/src/pycurb/core/algorithms/leaky_bucket_async.py +42 -0
  29. pycurb-0.1.0/src/pycurb/core/algorithms/sliding_window.py +25 -0
  30. pycurb-0.1.0/src/pycurb/core/algorithms/sliding_window_async.py +28 -0
  31. pycurb-0.1.0/src/pycurb/core/algorithms/token_bucket.py +39 -0
  32. pycurb-0.1.0/src/pycurb/core/algorithms/token_bucket_async.py +41 -0
  33. pycurb-0.1.0/src/pycurb/core/decorators.py +155 -0
  34. pycurb-0.1.0/src/pycurb/core/limiter.py +114 -0
  35. pycurb-0.1.0/src/pycurb/core/limiter_async.py +123 -0
  36. pycurb-0.1.0/src/pycurb/core/models.py +271 -0
  37. pycurb-0.1.0/src/pycurb/core/resolver.py +97 -0
  38. pycurb-0.1.0/src/pycurb/core/storage/__init__.py +8 -0
  39. pycurb-0.1.0/src/pycurb/core/storage/base.py +123 -0
  40. pycurb-0.1.0/src/pycurb/core/storage/base_async.py +123 -0
  41. pycurb-0.1.0/src/pycurb/core/storage/memory.py +156 -0
  42. pycurb-0.1.0/src/pycurb/core/storage/memory_async.py +156 -0
  43. pycurb-0.1.0/src/pycurb/core/storage/redis.py +360 -0
  44. pycurb-0.1.0/src/pycurb/core/storage/redis_async.py +371 -0
  45. pycurb-0.1.0/src/pycurb/utils.py +111 -0
  46. pycurb-0.1.0/src/pycurb.egg-info/PKG-INFO +256 -0
  47. pycurb-0.1.0/src/pycurb.egg-info/SOURCES.txt +49 -0
  48. pycurb-0.1.0/src/pycurb.egg-info/dependency_links.txt +1 -0
  49. pycurb-0.1.0/src/pycurb.egg-info/requires.txt +29 -0
  50. pycurb-0.1.0/src/pycurb.egg-info/top_level.txt +1 -0
  51. pycurb-0.1.0/tests/test_utils.py +166 -0
pycurb-0.1.0/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
pycurb-0.1.0/PKG-INFO ADDED
@@ -0,0 +1,256 @@
1
+ Metadata-Version: 2.4
2
+ Name: pycurb
3
+ Version: 0.1.0
4
+ Summary: A framework-agnostic Python rate limit library
5
+ Author-email: Oluwaseun Ogunsanu <ogunsanu17@gmail.com>
6
+ License-Expression: Apache-2.0
7
+ Project-URL: Homepage, https://github.com/fore-site/pycurb
8
+ Project-URL: Repository, https://github.com/fore-site/pycurb
9
+ Project-URL: Documentation, https://pycurb.readthedocs.io/
10
+ Classifier: Programming Language :: Python :: 3.10
11
+ Classifier: Programming Language :: Python :: 3.11
12
+ Classifier: Programming Language :: Python :: 3.12
13
+ Classifier: Programming Language :: Python :: 3.13
14
+ Classifier: Operating System :: OS Independent
15
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
16
+ Requires-Python: >=3.10
17
+ Description-Content-Type: text/markdown
18
+ License-File: LICENSE
19
+ Requires-Dist: pydantic>=2.13.4
20
+ Provides-Extra: fastapi
21
+ Requires-Dist: fastapi>=0.137.0; extra == "fastapi"
22
+ Requires-Dist: starlette>=1.0.0; extra == "fastapi"
23
+ Provides-Extra: django
24
+ Requires-Dist: django>=5.2.15; extra == "django"
25
+ Provides-Extra: flask
26
+ Requires-Dist: flask>=3.0.0; extra == "flask"
27
+ Requires-Dist: flask-login>=0.6.3; extra == "flask"
28
+ Provides-Extra: redis
29
+ Requires-Dist: redis>=8.0.0; extra == "redis"
30
+ Provides-Extra: all
31
+ Requires-Dist: pycurb[redis]; extra == "all"
32
+ Requires-Dist: pycurb[fastapi]; extra == "all"
33
+ Requires-Dist: pycurb[django]; extra == "all"
34
+ Requires-Dist: pycurb[flask]; extra == "all"
35
+ Provides-Extra: docs
36
+ Requires-Dist: mkdocs>=1.6.1; extra == "docs"
37
+ Requires-Dist: mkdocs-git-revision-date-localized-plugin>=1.5.3; extra == "docs"
38
+ Requires-Dist: mkdocs-material>=9.7.6; extra == "docs"
39
+ Requires-Dist: mkdocstrings-python>=2.0.5; extra == "docs"
40
+ Requires-Dist: mkdocstrings-python-xref>=2.1.1; extra == "docs"
41
+ Requires-Dist: ruff>=0.15.18; extra == "docs"
42
+ Dynamic: license-file
43
+
44
+ # PyCurb – A Framework‑Agnostic Rate Limiter for Python
45
+
46
+ [![CI](https://github.com/fore-site/pycurb/actions/workflows/test.yml/badge.svg)](https://github.com/fore-site/pycurb/actions)
47
+ [![License: Apache 2.0](https://img.shields.io/badge/License-Apache%202.0-blue.svg)](https://www.apache.org/licenses/LICENSE-2.0)
48
+ [![Documentation Status](https://readthedocs.org/projects/pycurb/badge/?version=latest)](https://pycurb.readthedocs.io/en/latest/?badge=latest)
49
+
50
+ **PyCurb** is a flexible, and easy‑to‑use rate‑limiting library for Python. It is desgined to be **framework‑agnostic**, i.e, used with FastAPI, Flask, Django, or even in plain scripts and CLI tools. It supports multiple algorithms, redis & in-memory storage backends, and has advanced features like composite (multi‑tier) limits, and dynamic rule updates.
51
+
52
+ ## Algorithms
53
+
54
+ PyCurb implements five industry‑standard rate‑limiting algorithms, each suited for different traffic patterns. Choose the one that best fits your use case.
55
+
56
+ ### 1. Sliding Window
57
+
58
+ The sliding window algorithm maintains a **queue of request timestamps** for each key. The window slides continuously; old timestamps (older than `now - window`) are discarded. At any moment, the number of requests in the window is the length of the queue.
59
+
60
+ - **Use case**: APIs where you need strict, real‑time limiting without the burstiness of fixed windows.
61
+ - **Parameters**: `limit` (max requests), `window` (duration in seconds).
62
+ - **Behaviour**: The window moves with every request; no abrupt resets.
63
+
64
+ **Example**
65
+ Limit: `100 requests per minute`.
66
+ At `t=10s`, a request arrives; its timestamp is stored. At `t=75s`, the window covers `[15s, 75s]`; any request older than `15s` is dropped. The count is the number of timestamps in that range.
67
+
68
+ `count = |{ t ∈ timestamps : t > now - window }|`
69
+ Allowed if `count < limit`.
70
+
71
+ ### 2. Fixed Window
72
+
73
+ Fixed window divides time into consecutive, non‑overlapping windows of length `window`. All requests within the same window are counted together. The counter resets at the start of each new window.
74
+
75
+ - **Use case**: Simple, memory‑efficient limiting for non‑critical APIs.
76
+ - **Parameters**: `limit` (max requests per window), `window` (duration in seconds).
77
+ - **Behaviour**: The counter resets abruptly at window boundaries.
78
+
79
+ **Example**
80
+ Limit: `100 requests per minute`, windows start at `0s`, `60s`, `120s`, …
81
+ At `t=10s`, the counter is in window `[0,60)`. At `t=75s`, a new window `[60,120)` begins and the counter resets to `0`.
82
+
83
+ `window_start = floor(now / window) * window`
84
+ `counter` is stored for the current `window_start`.
85
+ Allowed if `counter < limit`.
86
+
87
+ ### 3. Token Bucket
88
+
89
+ The token bucket algorithm maintains a **bucket of tokens** that refills at a constant rate. Each request consumes one token. If the bucket has at least one token, the request is allowed; otherwise, it is denied.
90
+
91
+ - **Use case**: APIs that require a steady average rate with the ability to handle short bursts.
92
+ - **Parameters**: `capacity` (burst size), `refill_rate` (tokens per second).
93
+ - **Behaviour**: Allows bursts up to `capacity`; long‑term average is `refill_rate`.
94
+
95
+ **Example**
96
+ Capacity = `10`, refill rate = `2 tokens/sec`.
97
+ Initially, the bucket has `10` tokens. A client can send `10` requests immediately (burst). After that, the bucket refills at `2 tokens/sec`, so the client can sustain `2` requests per second over time.
98
+
99
+ `tokens = min(capacity, tokens + (now - last_refill) * refill_rate)`
100
+ Allowed if `tokens >= 1`; then `tokens -= 1`.
101
+
102
+ ### 4. Leaky Bucket
103
+
104
+ The leaky bucket algorithm models a **queue** that holds pending requests. Requests leak out of the queue at a constant rate (`leak_rate`). New requests are accepted only if the queue has free capacity.
105
+
106
+ - **Use case**: Smoothing bursty traffic to a constant output rate (e.g., for database writes or external API calls).
107
+ - **Parameters**: `capacity` (max queue size), `leak_rate` (requests per second).
108
+ - **Behaviour**: Smooths bursts; the output rate is constant.
109
+
110
+ **Example**
111
+ Capacity = `5`, leak rate = `1 request/sec`.
112
+ If `5` requests arrive at once, they fill the queue. They are then processed at `1 request/sec`. A new request arriving while the queue is full is dropped.
113
+
114
+ `leaked = floor((now - last_leak) * leak_rate)`
115
+ `queue = max(0, queue - leaked)`
116
+ Allowed if `queue < capacity`; then `queue += 1`.
117
+
118
+ ### 5. GCRA – Generic Cell Rate Algorithm
119
+
120
+ GCRA (also known as the **leaky bucket with burst control**) uses a single state variable – the **Theoretical Arrival Time (TAT)** – to enforce both a rate and a burst size. It does not require a queue or background processes.
121
+
122
+ - **Use case**: High‑precision rate limiting where both burst and average rate must be controlled.
123
+ - **Parameters**: `capacity` (burst size), `refill_rate` (requests per second).
124
+ - **Behaviour**: Similar to token bucket but implemented with a single timestamp, making it extremely efficient.
125
+
126
+ **Example**
127
+ Capacity = `10`, rate = `5 req/sec` → interval `T = 0.2s`, burst interval `τ = capacity * T = 2s`.
128
+ The algorithm allows a request if `TAT ≤ now + τ`. After an allowed request, `TAT = max(TAT, now) + T`. This ensures that the average rate is `5 req/sec` and the burst is at most `10` requests.
129
+
130
+ `T = 1 / refill_rate`
131
+ `τ = (capacity - 1) * T` _(using `capacity-1` to match the burst size exactly)_
132
+ Allowed if `TAT ≤ now + τ`.
133
+ If allowed: `TAT = max(TAT, now) + T`.
134
+
135
+ ### Comparison Table
136
+
137
+ | Algorithm | Burst Tolerance | Memory Usage | Best For |
138
+ | -------------- | --------------- | ------------------- | ---------------------------------- |
139
+ | Sliding Window | Up to limit | Medium (timestamps) | Precise window limits |
140
+ | Fixed Window | Up to limit | Low (counter) | Simple, low‑overhead limiting |
141
+ | Token Bucket | Configurable | Low (2 floats) | Burst‑tolerant APIs |
142
+ | Leaky Bucket | None (smooths) | Low (2 floats) | Constant‑rate processing |
143
+ | GCRA | Configurable | Low (1 float) | High‑precision, efficient limiting |
144
+
145
+ Choose the algorithm that aligns with your traffic pattern and resource constraints. All algorithms are fully configurable via the `LimitRule` model.
146
+
147
+ ---
148
+
149
+ ## Get Started
150
+
151
+ ### Installation
152
+
153
+ Install the core package:
154
+
155
+ ```
156
+ pip install pycurb
157
+ ```
158
+
159
+ For redis as a storage backend, install:
160
+
161
+ ```
162
+ pip install pycurb[redis]
163
+ ```
164
+
165
+ For framework adapters (i.e Flask, Django, FastAPI), install the extras:
166
+
167
+ ```
168
+ pip install pycurb[fastapi]
169
+ ```
170
+
171
+ To install everything:
172
+
173
+ ```
174
+ pip install pycurb[all]
175
+ ```
176
+
177
+ ### Basic Usage (Async)
178
+
179
+ ```
180
+ import asyncio
181
+ import time
182
+ from pycurb.core import AsyncRateLimiter, AsyncMemoryStorage, LimitRule
183
+ ```
184
+
185
+ 1. Define a rule: 5 requests per 10 seconds
186
+
187
+ ```
188
+ rule = LimitRule(
189
+ name="api",
190
+ algorithm="sliding_window",
191
+ limit=5,
192
+ window=10,
193
+ )
194
+ ```
195
+
196
+ 2. Set up storage and limiter
197
+
198
+ ```
199
+ storage = AsyncMemoryStorage()
200
+ limiter = AsyncRateLimiter(storage, [rule])
201
+ ```
202
+
203
+ 3. Use it in your async function
204
+
205
+ ```
206
+ async def fetch_data(user_id: str):
207
+ result = await limiter.check(user_id, "api")
208
+ if result.allowed:
209
+ print(f"Allowed – remaining: {result.remaining}")
210
+ else:
211
+ print(f"Denied – retry after: {result.retry_after}")
212
+
213
+ asyncio.run(fetch_data("user-123"))
214
+ ```
215
+
216
+ ### Basic Usage (Sync)
217
+
218
+ ```
219
+ from pycurb.core import RateLimiter, MemoryStorage, LimitRule
220
+
221
+ storage = MemoryStorage()
222
+ limiter = RateLimiter(storage, [rule])
223
+
224
+ def handle_request(user_id: str):
225
+ result = limiter.check(user_id, "api")
226
+ if result.allowed:
227
+ print("Request allowed")
228
+ else:
229
+ print(f"Rate limited. Retry after {result.retry_after} seconds.")
230
+ ```
231
+
232
+ ### Using the Decorator
233
+
234
+ The `@rate_limit` decorator wraps any sync or async function
235
+
236
+ ```
237
+ from pycurb.core import rate_limit
238
+
239
+ @rate_limit(limiter, limit_str="5/10s", key_extractor=lambda user_id: str(user_id))
240
+ async def my_function(user_id: str):
241
+ return "OK"
242
+ ```
243
+
244
+ ### Framework Adapters
245
+
246
+ Pycurb provides plug-and-play adapters for popular python frameworks
247
+
248
+ - FastAPI: Use the `RateLimitMiddleware` class or `rate_limiter` dependency
249
+ - Django: Use the `rate_limit` decorator or the `create_rate_limit_middleware` factory
250
+ - Flask: Use the `rate_limit` decorator or the `RateLimit` extension
251
+
252
+ ---
253
+
254
+ ## Links
255
+
256
+ - [Documentation](https://pycurb.readthedocs.io/en/latest)
pycurb-0.1.0/README.md ADDED
@@ -0,0 +1,213 @@
1
+ # PyCurb – A Framework‑Agnostic Rate Limiter for Python
2
+
3
+ [![CI](https://github.com/fore-site/pycurb/actions/workflows/test.yml/badge.svg)](https://github.com/fore-site/pycurb/actions)
4
+ [![License: Apache 2.0](https://img.shields.io/badge/License-Apache%202.0-blue.svg)](https://www.apache.org/licenses/LICENSE-2.0)
5
+ [![Documentation Status](https://readthedocs.org/projects/pycurb/badge/?version=latest)](https://pycurb.readthedocs.io/en/latest/?badge=latest)
6
+
7
+ **PyCurb** is a flexible, and easy‑to‑use rate‑limiting library for Python. It is desgined to be **framework‑agnostic**, i.e, used with FastAPI, Flask, Django, or even in plain scripts and CLI tools. It supports multiple algorithms, redis & in-memory storage backends, and has advanced features like composite (multi‑tier) limits, and dynamic rule updates.
8
+
9
+ ## Algorithms
10
+
11
+ PyCurb implements five industry‑standard rate‑limiting algorithms, each suited for different traffic patterns. Choose the one that best fits your use case.
12
+
13
+ ### 1. Sliding Window
14
+
15
+ The sliding window algorithm maintains a **queue of request timestamps** for each key. The window slides continuously; old timestamps (older than `now - window`) are discarded. At any moment, the number of requests in the window is the length of the queue.
16
+
17
+ - **Use case**: APIs where you need strict, real‑time limiting without the burstiness of fixed windows.
18
+ - **Parameters**: `limit` (max requests), `window` (duration in seconds).
19
+ - **Behaviour**: The window moves with every request; no abrupt resets.
20
+
21
+ **Example**
22
+ Limit: `100 requests per minute`.
23
+ At `t=10s`, a request arrives; its timestamp is stored. At `t=75s`, the window covers `[15s, 75s]`; any request older than `15s` is dropped. The count is the number of timestamps in that range.
24
+
25
+ `count = |{ t ∈ timestamps : t > now - window }|`
26
+ Allowed if `count < limit`.
27
+
28
+ ### 2. Fixed Window
29
+
30
+ Fixed window divides time into consecutive, non‑overlapping windows of length `window`. All requests within the same window are counted together. The counter resets at the start of each new window.
31
+
32
+ - **Use case**: Simple, memory‑efficient limiting for non‑critical APIs.
33
+ - **Parameters**: `limit` (max requests per window), `window` (duration in seconds).
34
+ - **Behaviour**: The counter resets abruptly at window boundaries.
35
+
36
+ **Example**
37
+ Limit: `100 requests per minute`, windows start at `0s`, `60s`, `120s`, …
38
+ At `t=10s`, the counter is in window `[0,60)`. At `t=75s`, a new window `[60,120)` begins and the counter resets to `0`.
39
+
40
+ `window_start = floor(now / window) * window`
41
+ `counter` is stored for the current `window_start`.
42
+ Allowed if `counter < limit`.
43
+
44
+ ### 3. Token Bucket
45
+
46
+ The token bucket algorithm maintains a **bucket of tokens** that refills at a constant rate. Each request consumes one token. If the bucket has at least one token, the request is allowed; otherwise, it is denied.
47
+
48
+ - **Use case**: APIs that require a steady average rate with the ability to handle short bursts.
49
+ - **Parameters**: `capacity` (burst size), `refill_rate` (tokens per second).
50
+ - **Behaviour**: Allows bursts up to `capacity`; long‑term average is `refill_rate`.
51
+
52
+ **Example**
53
+ Capacity = `10`, refill rate = `2 tokens/sec`.
54
+ Initially, the bucket has `10` tokens. A client can send `10` requests immediately (burst). After that, the bucket refills at `2 tokens/sec`, so the client can sustain `2` requests per second over time.
55
+
56
+ `tokens = min(capacity, tokens + (now - last_refill) * refill_rate)`
57
+ Allowed if `tokens >= 1`; then `tokens -= 1`.
58
+
59
+ ### 4. Leaky Bucket
60
+
61
+ The leaky bucket algorithm models a **queue** that holds pending requests. Requests leak out of the queue at a constant rate (`leak_rate`). New requests are accepted only if the queue has free capacity.
62
+
63
+ - **Use case**: Smoothing bursty traffic to a constant output rate (e.g., for database writes or external API calls).
64
+ - **Parameters**: `capacity` (max queue size), `leak_rate` (requests per second).
65
+ - **Behaviour**: Smooths bursts; the output rate is constant.
66
+
67
+ **Example**
68
+ Capacity = `5`, leak rate = `1 request/sec`.
69
+ If `5` requests arrive at once, they fill the queue. They are then processed at `1 request/sec`. A new request arriving while the queue is full is dropped.
70
+
71
+ `leaked = floor((now - last_leak) * leak_rate)`
72
+ `queue = max(0, queue - leaked)`
73
+ Allowed if `queue < capacity`; then `queue += 1`.
74
+
75
+ ### 5. GCRA – Generic Cell Rate Algorithm
76
+
77
+ GCRA (also known as the **leaky bucket with burst control**) uses a single state variable – the **Theoretical Arrival Time (TAT)** – to enforce both a rate and a burst size. It does not require a queue or background processes.
78
+
79
+ - **Use case**: High‑precision rate limiting where both burst and average rate must be controlled.
80
+ - **Parameters**: `capacity` (burst size), `refill_rate` (requests per second).
81
+ - **Behaviour**: Similar to token bucket but implemented with a single timestamp, making it extremely efficient.
82
+
83
+ **Example**
84
+ Capacity = `10`, rate = `5 req/sec` → interval `T = 0.2s`, burst interval `τ = capacity * T = 2s`.
85
+ The algorithm allows a request if `TAT ≤ now + τ`. After an allowed request, `TAT = max(TAT, now) + T`. This ensures that the average rate is `5 req/sec` and the burst is at most `10` requests.
86
+
87
+ `T = 1 / refill_rate`
88
+ `τ = (capacity - 1) * T` _(using `capacity-1` to match the burst size exactly)_
89
+ Allowed if `TAT ≤ now + τ`.
90
+ If allowed: `TAT = max(TAT, now) + T`.
91
+
92
+ ### Comparison Table
93
+
94
+ | Algorithm | Burst Tolerance | Memory Usage | Best For |
95
+ | -------------- | --------------- | ------------------- | ---------------------------------- |
96
+ | Sliding Window | Up to limit | Medium (timestamps) | Precise window limits |
97
+ | Fixed Window | Up to limit | Low (counter) | Simple, low‑overhead limiting |
98
+ | Token Bucket | Configurable | Low (2 floats) | Burst‑tolerant APIs |
99
+ | Leaky Bucket | None (smooths) | Low (2 floats) | Constant‑rate processing |
100
+ | GCRA | Configurable | Low (1 float) | High‑precision, efficient limiting |
101
+
102
+ Choose the algorithm that aligns with your traffic pattern and resource constraints. All algorithms are fully configurable via the `LimitRule` model.
103
+
104
+ ---
105
+
106
+ ## Get Started
107
+
108
+ ### Installation
109
+
110
+ Install the core package:
111
+
112
+ ```
113
+ pip install pycurb
114
+ ```
115
+
116
+ For redis as a storage backend, install:
117
+
118
+ ```
119
+ pip install pycurb[redis]
120
+ ```
121
+
122
+ For framework adapters (i.e Flask, Django, FastAPI), install the extras:
123
+
124
+ ```
125
+ pip install pycurb[fastapi]
126
+ ```
127
+
128
+ To install everything:
129
+
130
+ ```
131
+ pip install pycurb[all]
132
+ ```
133
+
134
+ ### Basic Usage (Async)
135
+
136
+ ```
137
+ import asyncio
138
+ import time
139
+ from pycurb.core import AsyncRateLimiter, AsyncMemoryStorage, LimitRule
140
+ ```
141
+
142
+ 1. Define a rule: 5 requests per 10 seconds
143
+
144
+ ```
145
+ rule = LimitRule(
146
+ name="api",
147
+ algorithm="sliding_window",
148
+ limit=5,
149
+ window=10,
150
+ )
151
+ ```
152
+
153
+ 2. Set up storage and limiter
154
+
155
+ ```
156
+ storage = AsyncMemoryStorage()
157
+ limiter = AsyncRateLimiter(storage, [rule])
158
+ ```
159
+
160
+ 3. Use it in your async function
161
+
162
+ ```
163
+ async def fetch_data(user_id: str):
164
+ result = await limiter.check(user_id, "api")
165
+ if result.allowed:
166
+ print(f"Allowed – remaining: {result.remaining}")
167
+ else:
168
+ print(f"Denied – retry after: {result.retry_after}")
169
+
170
+ asyncio.run(fetch_data("user-123"))
171
+ ```
172
+
173
+ ### Basic Usage (Sync)
174
+
175
+ ```
176
+ from pycurb.core import RateLimiter, MemoryStorage, LimitRule
177
+
178
+ storage = MemoryStorage()
179
+ limiter = RateLimiter(storage, [rule])
180
+
181
+ def handle_request(user_id: str):
182
+ result = limiter.check(user_id, "api")
183
+ if result.allowed:
184
+ print("Request allowed")
185
+ else:
186
+ print(f"Rate limited. Retry after {result.retry_after} seconds.")
187
+ ```
188
+
189
+ ### Using the Decorator
190
+
191
+ The `@rate_limit` decorator wraps any sync or async function
192
+
193
+ ```
194
+ from pycurb.core import rate_limit
195
+
196
+ @rate_limit(limiter, limit_str="5/10s", key_extractor=lambda user_id: str(user_id))
197
+ async def my_function(user_id: str):
198
+ return "OK"
199
+ ```
200
+
201
+ ### Framework Adapters
202
+
203
+ Pycurb provides plug-and-play adapters for popular python frameworks
204
+
205
+ - FastAPI: Use the `RateLimitMiddleware` class or `rate_limiter` dependency
206
+ - Django: Use the `rate_limit` decorator or the `create_rate_limit_middleware` factory
207
+ - Flask: Use the `rate_limit` decorator or the `RateLimit` extension
208
+
209
+ ---
210
+
211
+ ## Links
212
+
213
+ - [Documentation](https://pycurb.readthedocs.io/en/latest)