qubrixa-mail 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.
- qubrixa_mail-0.1.0/LICENSE +21 -0
- qubrixa_mail-0.1.0/PKG-INFO +156 -0
- qubrixa_mail-0.1.0/README.md +122 -0
- qubrixa_mail-0.1.0/pyproject.toml +49 -0
- qubrixa_mail-0.1.0/setup.cfg +4 -0
- qubrixa_mail-0.1.0/src/qubrixa_mail/__init__.py +48 -0
- qubrixa_mail-0.1.0/src/qubrixa_mail/_base.py +194 -0
- qubrixa_mail-0.1.0/src/qubrixa_mail/_ratelimit.py +99 -0
- qubrixa_mail-0.1.0/src/qubrixa_mail/_version.py +1 -0
- qubrixa_mail-0.1.0/src/qubrixa_mail/async_client.py +216 -0
- qubrixa_mail-0.1.0/src/qubrixa_mail/cli.py +90 -0
- qubrixa_mail-0.1.0/src/qubrixa_mail/client.py +233 -0
- qubrixa_mail-0.1.0/src/qubrixa_mail/exceptions.py +77 -0
- qubrixa_mail-0.1.0/src/qubrixa_mail/models.py +177 -0
- qubrixa_mail-0.1.0/src/qubrixa_mail/py.typed +0 -0
- qubrixa_mail-0.1.0/src/qubrixa_mail.egg-info/PKG-INFO +156 -0
- qubrixa_mail-0.1.0/src/qubrixa_mail.egg-info/SOURCES.txt +20 -0
- qubrixa_mail-0.1.0/src/qubrixa_mail.egg-info/dependency_links.txt +1 -0
- qubrixa_mail-0.1.0/src/qubrixa_mail.egg-info/entry_points.txt +2 -0
- qubrixa_mail-0.1.0/src/qubrixa_mail.egg-info/requires.txt +9 -0
- qubrixa_mail-0.1.0/src/qubrixa_mail.egg-info/top_level.txt +1 -0
- qubrixa_mail-0.1.0/tests/test_client.py +239 -0
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Its2Pawan
|
|
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.
|
|
@@ -0,0 +1,156 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: qubrixa-mail
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Unofficial Python client for the Qubrixa Mail disposable-inbox / OTP API
|
|
5
|
+
Author: Its2Pawan
|
|
6
|
+
Maintainer: Its2Pawan
|
|
7
|
+
License: MIT
|
|
8
|
+
Project-URL: Homepage, https://github.com/Its2Pawan/qubrixa-mail
|
|
9
|
+
Project-URL: Documentation, https://github.com/Its2Pawan/qubrixa-mail#readme
|
|
10
|
+
Project-URL: Issues, https://github.com/Its2Pawan/qubrixa-mail/issues
|
|
11
|
+
Keywords: qubrixa,disposable email,temp mail,otp,api client,testing
|
|
12
|
+
Classifier: Development Status :: 4 - Beta
|
|
13
|
+
Classifier: Intended Audience :: Developers
|
|
14
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
15
|
+
Classifier: Programming Language :: Python :: 3
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.8
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.9
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
19
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
20
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
21
|
+
Classifier: Typing :: Typed
|
|
22
|
+
Classifier: Topic :: Communications :: Email
|
|
23
|
+
Requires-Python: >=3.8
|
|
24
|
+
Description-Content-Type: text/markdown
|
|
25
|
+
License-File: LICENSE
|
|
26
|
+
Requires-Dist: requests>=2.25
|
|
27
|
+
Provides-Extra: async
|
|
28
|
+
Requires-Dist: httpx>=0.24; extra == "async"
|
|
29
|
+
Provides-Extra: dev
|
|
30
|
+
Requires-Dist: pytest>=7; extra == "dev"
|
|
31
|
+
Requires-Dist: build; extra == "dev"
|
|
32
|
+
Requires-Dist: twine; extra == "dev"
|
|
33
|
+
Dynamic: license-file
|
|
34
|
+
|
|
35
|
+
# qubrixa-mail
|
|
36
|
+
|
|
37
|
+
Unofficial Python client for the **Qubrixa Mail** Developer API: create disposable
|
|
38
|
+
inboxes, read messages, and extract OTP codes / verification links.
|
|
39
|
+
|
|
40
|
+
You need two things from your Qubrixa Mail account: the **base URL** and an **API key**
|
|
41
|
+
(generate one in the Developer Console).
|
|
42
|
+
|
|
43
|
+
## Install
|
|
44
|
+
|
|
45
|
+
```bash
|
|
46
|
+
pip install qubrixa-mail # sync client (requests)
|
|
47
|
+
pip install "qubrixa-mail[async]" # + async client (httpx)
|
|
48
|
+
```
|
|
49
|
+
|
|
50
|
+
## Quick start
|
|
51
|
+
|
|
52
|
+
```python
|
|
53
|
+
from qubrixa_mail import QubrixaMail
|
|
54
|
+
|
|
55
|
+
mail = QubrixaMail(
|
|
56
|
+
base_url="https://mail.qubrixa.in/api/v1", # your base URL
|
|
57
|
+
api_key="sk_live_your_secret_api_key_here", # your API key
|
|
58
|
+
)
|
|
59
|
+
|
|
60
|
+
inbox = mail.create_inbox(expires_in_seconds=3600)
|
|
61
|
+
print(inbox.address) # use this address on the site you are testing
|
|
62
|
+
|
|
63
|
+
otp = inbox.wait_for_otp(timeout=30) # long-polls until the email arrives
|
|
64
|
+
print(otp.otp, otp.verification_url)
|
|
65
|
+
|
|
66
|
+
inbox.delete()
|
|
67
|
+
```
|
|
68
|
+
|
|
69
|
+
Or configure through environment variables and write `QubrixaMail()`:
|
|
70
|
+
|
|
71
|
+
```bash
|
|
72
|
+
export QUBRIXA_BASE_URL="https://mail.qubrixa.in/api/v1"
|
|
73
|
+
export QUBRIXA_API_KEY="sk_live_..."
|
|
74
|
+
```
|
|
75
|
+
|
|
76
|
+
If you pass only a host (`https://mail.qubrixa.in`), `/api/v1` is appended automatically.
|
|
77
|
+
|
|
78
|
+
### Auto-cleanup
|
|
79
|
+
|
|
80
|
+
```python
|
|
81
|
+
with QubrixaMail() as mail:
|
|
82
|
+
with mail.temporary_inbox(expires_in_seconds=600) as inbox:
|
|
83
|
+
... # inbox is deleted when the block exits
|
|
84
|
+
```
|
|
85
|
+
|
|
86
|
+
### Async
|
|
87
|
+
|
|
88
|
+
```python
|
|
89
|
+
import asyncio
|
|
90
|
+
from qubrixa_mail import AsyncQubrixaMail
|
|
91
|
+
|
|
92
|
+
async def main():
|
|
93
|
+
async with AsyncQubrixaMail() as mail:
|
|
94
|
+
async with mail.temporary_inbox() as inbox:
|
|
95
|
+
otp = await mail.wait_for_otp(inbox, timeout=30)
|
|
96
|
+
print(otp.otp)
|
|
97
|
+
|
|
98
|
+
asyncio.run(main())
|
|
99
|
+
```
|
|
100
|
+
|
|
101
|
+
## API
|
|
102
|
+
|
|
103
|
+
| Method | Endpoint |
|
|
104
|
+
|---|---|
|
|
105
|
+
| `create_inbox(expires_in_seconds=, local_part=, webhook_url=, **extra)` | `POST /inboxes` |
|
|
106
|
+
| `delete_inbox(inbox)` | `DELETE /inboxes/{id}` |
|
|
107
|
+
| `list_messages(inbox, limit=)` | `GET /inboxes/{id}/messages` |
|
|
108
|
+
| `get_message(inbox, message_id)` | `GET /inboxes/{id}/messages/{message_id}` |
|
|
109
|
+
| `wait_for_otp(inbox, timeout=30)` | `GET /inboxes/{id_or_address}/wait-otp` |
|
|
110
|
+
| `latest_otp(inbox)` | `GET /inboxes/{id_or_address}/latest-otp` |
|
|
111
|
+
| `get_quota()` | `GET /quota` |
|
|
112
|
+
| `wait_for_message(inbox, timeout=, interval=, predicate=)` | polls `list_messages` (non-OTP mail) |
|
|
113
|
+
|
|
114
|
+
`inbox` can be an `Inbox` object, an inbox id, or (for the OTP endpoints) an email address.
|
|
115
|
+
Every returned object keeps the full server response in `.raw`.
|
|
116
|
+
|
|
117
|
+
## Rate limits & bans
|
|
118
|
+
|
|
119
|
+
The server allows **300 requests/min** and **10 inbox creations/min**, and suspends a
|
|
120
|
+
key + IP after **5 consecutive 429s within 5 minutes**. This client protects you:
|
|
121
|
+
|
|
122
|
+
* a built-in sliding-window limiter (default 270/min and 9/min) delays calls instead of failing;
|
|
123
|
+
* `429` is **never retried automatically** - `RateLimitError.retry_after` tells you how long to wait;
|
|
124
|
+
* after 3 consecutive 429s it raises `AbuseGuardError` locally without contacting the server;
|
|
125
|
+
* only `GET`/`DELETE` are retried on connection errors and 502/503/504 (never `POST`).
|
|
126
|
+
|
|
127
|
+
Disable the limiter with `QubrixaMail(..., rate_limit=False)`.
|
|
128
|
+
|
|
129
|
+
## Errors
|
|
130
|
+
|
|
131
|
+
`QubrixaError` -> `ConfigurationError`, `APIConnectionError`, `AbuseGuardError`,
|
|
132
|
+
`OTPTimeoutError`, and `APIError` -> `AuthenticationError` (401), `ForbiddenError` (403),
|
|
133
|
+
`NotFoundError` (404), `RateLimitError` (429), `ServiceUnavailableError` (503).
|
|
134
|
+
|
|
135
|
+
## CLI
|
|
136
|
+
|
|
137
|
+
```bash
|
|
138
|
+
qubrixa-mail create --expires-in 3600 --address-only
|
|
139
|
+
qubrixa-mail wait-otp test7391@samirjs.qzz.io --timeout 30 --otp-only
|
|
140
|
+
qubrixa-mail quota
|
|
141
|
+
```
|
|
142
|
+
|
|
143
|
+
## Responsible use
|
|
144
|
+
|
|
145
|
+
Use disposable inboxes only for services and accounts you are allowed to test, and follow the
|
|
146
|
+
terms of Qubrixa Mail and of every site you interact with. This is an unofficial community
|
|
147
|
+
library and is not affiliated with Qubrixa.
|
|
148
|
+
|
|
149
|
+
## Publish to PyPI
|
|
150
|
+
|
|
151
|
+
```bash
|
|
152
|
+
pip install build twine
|
|
153
|
+
python -m build
|
|
154
|
+
twine upload dist/*
|
|
155
|
+
```
|
|
156
|
+
Author / maintainer: **Its2Pawan**.
|
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
# qubrixa-mail
|
|
2
|
+
|
|
3
|
+
Unofficial Python client for the **Qubrixa Mail** Developer API: create disposable
|
|
4
|
+
inboxes, read messages, and extract OTP codes / verification links.
|
|
5
|
+
|
|
6
|
+
You need two things from your Qubrixa Mail account: the **base URL** and an **API key**
|
|
7
|
+
(generate one in the Developer Console).
|
|
8
|
+
|
|
9
|
+
## Install
|
|
10
|
+
|
|
11
|
+
```bash
|
|
12
|
+
pip install qubrixa-mail # sync client (requests)
|
|
13
|
+
pip install "qubrixa-mail[async]" # + async client (httpx)
|
|
14
|
+
```
|
|
15
|
+
|
|
16
|
+
## Quick start
|
|
17
|
+
|
|
18
|
+
```python
|
|
19
|
+
from qubrixa_mail import QubrixaMail
|
|
20
|
+
|
|
21
|
+
mail = QubrixaMail(
|
|
22
|
+
base_url="https://mail.qubrixa.in/api/v1", # your base URL
|
|
23
|
+
api_key="sk_live_your_secret_api_key_here", # your API key
|
|
24
|
+
)
|
|
25
|
+
|
|
26
|
+
inbox = mail.create_inbox(expires_in_seconds=3600)
|
|
27
|
+
print(inbox.address) # use this address on the site you are testing
|
|
28
|
+
|
|
29
|
+
otp = inbox.wait_for_otp(timeout=30) # long-polls until the email arrives
|
|
30
|
+
print(otp.otp, otp.verification_url)
|
|
31
|
+
|
|
32
|
+
inbox.delete()
|
|
33
|
+
```
|
|
34
|
+
|
|
35
|
+
Or configure through environment variables and write `QubrixaMail()`:
|
|
36
|
+
|
|
37
|
+
```bash
|
|
38
|
+
export QUBRIXA_BASE_URL="https://mail.qubrixa.in/api/v1"
|
|
39
|
+
export QUBRIXA_API_KEY="sk_live_..."
|
|
40
|
+
```
|
|
41
|
+
|
|
42
|
+
If you pass only a host (`https://mail.qubrixa.in`), `/api/v1` is appended automatically.
|
|
43
|
+
|
|
44
|
+
### Auto-cleanup
|
|
45
|
+
|
|
46
|
+
```python
|
|
47
|
+
with QubrixaMail() as mail:
|
|
48
|
+
with mail.temporary_inbox(expires_in_seconds=600) as inbox:
|
|
49
|
+
... # inbox is deleted when the block exits
|
|
50
|
+
```
|
|
51
|
+
|
|
52
|
+
### Async
|
|
53
|
+
|
|
54
|
+
```python
|
|
55
|
+
import asyncio
|
|
56
|
+
from qubrixa_mail import AsyncQubrixaMail
|
|
57
|
+
|
|
58
|
+
async def main():
|
|
59
|
+
async with AsyncQubrixaMail() as mail:
|
|
60
|
+
async with mail.temporary_inbox() as inbox:
|
|
61
|
+
otp = await mail.wait_for_otp(inbox, timeout=30)
|
|
62
|
+
print(otp.otp)
|
|
63
|
+
|
|
64
|
+
asyncio.run(main())
|
|
65
|
+
```
|
|
66
|
+
|
|
67
|
+
## API
|
|
68
|
+
|
|
69
|
+
| Method | Endpoint |
|
|
70
|
+
|---|---|
|
|
71
|
+
| `create_inbox(expires_in_seconds=, local_part=, webhook_url=, **extra)` | `POST /inboxes` |
|
|
72
|
+
| `delete_inbox(inbox)` | `DELETE /inboxes/{id}` |
|
|
73
|
+
| `list_messages(inbox, limit=)` | `GET /inboxes/{id}/messages` |
|
|
74
|
+
| `get_message(inbox, message_id)` | `GET /inboxes/{id}/messages/{message_id}` |
|
|
75
|
+
| `wait_for_otp(inbox, timeout=30)` | `GET /inboxes/{id_or_address}/wait-otp` |
|
|
76
|
+
| `latest_otp(inbox)` | `GET /inboxes/{id_or_address}/latest-otp` |
|
|
77
|
+
| `get_quota()` | `GET /quota` |
|
|
78
|
+
| `wait_for_message(inbox, timeout=, interval=, predicate=)` | polls `list_messages` (non-OTP mail) |
|
|
79
|
+
|
|
80
|
+
`inbox` can be an `Inbox` object, an inbox id, or (for the OTP endpoints) an email address.
|
|
81
|
+
Every returned object keeps the full server response in `.raw`.
|
|
82
|
+
|
|
83
|
+
## Rate limits & bans
|
|
84
|
+
|
|
85
|
+
The server allows **300 requests/min** and **10 inbox creations/min**, and suspends a
|
|
86
|
+
key + IP after **5 consecutive 429s within 5 minutes**. This client protects you:
|
|
87
|
+
|
|
88
|
+
* a built-in sliding-window limiter (default 270/min and 9/min) delays calls instead of failing;
|
|
89
|
+
* `429` is **never retried automatically** - `RateLimitError.retry_after` tells you how long to wait;
|
|
90
|
+
* after 3 consecutive 429s it raises `AbuseGuardError` locally without contacting the server;
|
|
91
|
+
* only `GET`/`DELETE` are retried on connection errors and 502/503/504 (never `POST`).
|
|
92
|
+
|
|
93
|
+
Disable the limiter with `QubrixaMail(..., rate_limit=False)`.
|
|
94
|
+
|
|
95
|
+
## Errors
|
|
96
|
+
|
|
97
|
+
`QubrixaError` -> `ConfigurationError`, `APIConnectionError`, `AbuseGuardError`,
|
|
98
|
+
`OTPTimeoutError`, and `APIError` -> `AuthenticationError` (401), `ForbiddenError` (403),
|
|
99
|
+
`NotFoundError` (404), `RateLimitError` (429), `ServiceUnavailableError` (503).
|
|
100
|
+
|
|
101
|
+
## CLI
|
|
102
|
+
|
|
103
|
+
```bash
|
|
104
|
+
qubrixa-mail create --expires-in 3600 --address-only
|
|
105
|
+
qubrixa-mail wait-otp test7391@samirjs.qzz.io --timeout 30 --otp-only
|
|
106
|
+
qubrixa-mail quota
|
|
107
|
+
```
|
|
108
|
+
|
|
109
|
+
## Responsible use
|
|
110
|
+
|
|
111
|
+
Use disposable inboxes only for services and accounts you are allowed to test, and follow the
|
|
112
|
+
terms of Qubrixa Mail and of every site you interact with. This is an unofficial community
|
|
113
|
+
library and is not affiliated with Qubrixa.
|
|
114
|
+
|
|
115
|
+
## Publish to PyPI
|
|
116
|
+
|
|
117
|
+
```bash
|
|
118
|
+
pip install build twine
|
|
119
|
+
python -m build
|
|
120
|
+
twine upload dist/*
|
|
121
|
+
```
|
|
122
|
+
Author / maintainer: **Its2Pawan**.
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["setuptools>=61", "wheel"]
|
|
3
|
+
build-backend = "setuptools.build_meta"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "qubrixa-mail"
|
|
7
|
+
dynamic = ["version"]
|
|
8
|
+
description = "Unofficial Python client for the Qubrixa Mail disposable-inbox / OTP API"
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
requires-python = ">=3.8"
|
|
11
|
+
license = {text = "MIT"}
|
|
12
|
+
authors = [{name = "Its2Pawan"}]
|
|
13
|
+
maintainers = [{name = "Its2Pawan"}]
|
|
14
|
+
keywords = ["qubrixa", "disposable email", "temp mail", "otp", "api client", "testing"]
|
|
15
|
+
classifiers = [
|
|
16
|
+
"Development Status :: 4 - Beta",
|
|
17
|
+
"Intended Audience :: Developers",
|
|
18
|
+
"License :: OSI Approved :: MIT License",
|
|
19
|
+
"Programming Language :: Python :: 3",
|
|
20
|
+
"Programming Language :: Python :: 3.8",
|
|
21
|
+
"Programming Language :: Python :: 3.9",
|
|
22
|
+
"Programming Language :: Python :: 3.10",
|
|
23
|
+
"Programming Language :: Python :: 3.11",
|
|
24
|
+
"Programming Language :: Python :: 3.12",
|
|
25
|
+
"Typing :: Typed",
|
|
26
|
+
"Topic :: Communications :: Email",
|
|
27
|
+
]
|
|
28
|
+
dependencies = ["requests>=2.25"]
|
|
29
|
+
|
|
30
|
+
[project.optional-dependencies]
|
|
31
|
+
async = ["httpx>=0.24"]
|
|
32
|
+
dev = ["pytest>=7", "build", "twine"]
|
|
33
|
+
|
|
34
|
+
[project.scripts]
|
|
35
|
+
qubrixa-mail = "qubrixa_mail.cli:main"
|
|
36
|
+
|
|
37
|
+
[project.urls]
|
|
38
|
+
Homepage = "https://github.com/Its2Pawan/qubrixa-mail"
|
|
39
|
+
Documentation = "https://github.com/Its2Pawan/qubrixa-mail#readme"
|
|
40
|
+
Issues = "https://github.com/Its2Pawan/qubrixa-mail/issues"
|
|
41
|
+
|
|
42
|
+
[tool.setuptools.dynamic]
|
|
43
|
+
version = {attr = "qubrixa_mail._version.__version__"}
|
|
44
|
+
|
|
45
|
+
[tool.setuptools.packages.find]
|
|
46
|
+
where = ["src"]
|
|
47
|
+
|
|
48
|
+
[tool.setuptools.package-data]
|
|
49
|
+
qubrixa_mail = ["py.typed"]
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
"""qubrixa-mail - Python client for the Qubrixa Mail disposable-inbox API."""
|
|
2
|
+
|
|
3
|
+
from ._version import __version__
|
|
4
|
+
from .client import QubrixaMail
|
|
5
|
+
from .exceptions import (
|
|
6
|
+
AbuseGuardError,
|
|
7
|
+
APIConnectionError,
|
|
8
|
+
APIError,
|
|
9
|
+
AuthenticationError,
|
|
10
|
+
ConfigurationError,
|
|
11
|
+
ForbiddenError,
|
|
12
|
+
NotFoundError,
|
|
13
|
+
OTPTimeoutError,
|
|
14
|
+
QubrixaError,
|
|
15
|
+
RateLimitError,
|
|
16
|
+
ServiceUnavailableError,
|
|
17
|
+
)
|
|
18
|
+
from .models import Inbox, Message, MessageSummary, OTPResult, Quota
|
|
19
|
+
|
|
20
|
+
__all__ = [
|
|
21
|
+
"__version__",
|
|
22
|
+
"QubrixaMail",
|
|
23
|
+
"AsyncQubrixaMail",
|
|
24
|
+
"Inbox",
|
|
25
|
+
"Message",
|
|
26
|
+
"MessageSummary",
|
|
27
|
+
"OTPResult",
|
|
28
|
+
"Quota",
|
|
29
|
+
"QubrixaError",
|
|
30
|
+
"ConfigurationError",
|
|
31
|
+
"APIConnectionError",
|
|
32
|
+
"APIError",
|
|
33
|
+
"AuthenticationError",
|
|
34
|
+
"ForbiddenError",
|
|
35
|
+
"NotFoundError",
|
|
36
|
+
"RateLimitError",
|
|
37
|
+
"ServiceUnavailableError",
|
|
38
|
+
"OTPTimeoutError",
|
|
39
|
+
"AbuseGuardError",
|
|
40
|
+
]
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def __getattr__(name): # lazy import so httpx stays an optional dependency
|
|
44
|
+
if name == "AsyncQubrixaMail":
|
|
45
|
+
from .async_client import AsyncQubrixaMail
|
|
46
|
+
|
|
47
|
+
return AsyncQubrixaMail
|
|
48
|
+
raise AttributeError("module %r has no attribute %r" % (__name__, name))
|
|
@@ -0,0 +1,194 @@
|
|
|
1
|
+
"""Logic shared by the sync and async clients (no network I/O in here)."""
|
|
2
|
+
|
|
3
|
+
import json as _json
|
|
4
|
+
import os
|
|
5
|
+
import random
|
|
6
|
+
from typing import Any, Dict, Mapping, Optional, Tuple, Union
|
|
7
|
+
from urllib.parse import quote, urlparse
|
|
8
|
+
|
|
9
|
+
from ._ratelimit import SlidingWindowLimiter, StrikeGuard
|
|
10
|
+
from ._version import __version__
|
|
11
|
+
from .exceptions import (
|
|
12
|
+
APIError,
|
|
13
|
+
AuthenticationError,
|
|
14
|
+
ConfigurationError,
|
|
15
|
+
ForbiddenError,
|
|
16
|
+
NotFoundError,
|
|
17
|
+
RateLimitError,
|
|
18
|
+
ServiceUnavailableError,
|
|
19
|
+
)
|
|
20
|
+
from .models import Inbox
|
|
21
|
+
|
|
22
|
+
ENV_BASE_URL = "QUBRIXA_BASE_URL"
|
|
23
|
+
ENV_API_KEY = "QUBRIXA_API_KEY"
|
|
24
|
+
DEFAULT_API_PATH = "/api/v1"
|
|
25
|
+
|
|
26
|
+
RETRY_STATUSES = frozenset({502, 503, 504})
|
|
27
|
+
IDEMPOTENT_METHODS = frozenset({"GET", "DELETE"})
|
|
28
|
+
|
|
29
|
+
InboxRef = Union[Inbox, str]
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def normalize_base_url(base_url: str) -> str:
|
|
33
|
+
"""Validate the URL; add ``/api/v1`` when only a host was given."""
|
|
34
|
+
base_url = base_url.strip()
|
|
35
|
+
parsed = urlparse(base_url)
|
|
36
|
+
if parsed.scheme not in ("http", "https") or not parsed.netloc:
|
|
37
|
+
raise ConfigurationError(
|
|
38
|
+
"base_url must start with http:// or https:// (got %r)." % base_url
|
|
39
|
+
)
|
|
40
|
+
if parsed.path in ("", "/"):
|
|
41
|
+
base_url = base_url.rstrip("/") + DEFAULT_API_PATH
|
|
42
|
+
return base_url.rstrip("/")
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def _extract_message(payload: Any, fallback: str) -> str:
|
|
46
|
+
if isinstance(payload, dict):
|
|
47
|
+
for key in ("detail", "error", "message"):
|
|
48
|
+
value = payload.get(key)
|
|
49
|
+
if isinstance(value, str) and value:
|
|
50
|
+
return value
|
|
51
|
+
if isinstance(value, dict):
|
|
52
|
+
inner = value.get("message")
|
|
53
|
+
if isinstance(inner, str) and inner:
|
|
54
|
+
return inner
|
|
55
|
+
return fallback
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def _retry_after(headers: Mapping[str, str]) -> Optional[float]:
|
|
59
|
+
for key, value in headers.items():
|
|
60
|
+
if key.lower() == "retry-after":
|
|
61
|
+
try:
|
|
62
|
+
return max(float(value), 0.0)
|
|
63
|
+
except (TypeError, ValueError):
|
|
64
|
+
return None
|
|
65
|
+
return None
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def build_api_error(status: int, text: str, headers: Mapping[str, str]) -> APIError:
|
|
69
|
+
try:
|
|
70
|
+
payload = _json.loads(text) if text else None
|
|
71
|
+
except ValueError:
|
|
72
|
+
payload = None
|
|
73
|
+
message = _extract_message(payload, (text or "").strip()[:300] or "Request failed")
|
|
74
|
+
kwargs = dict(status_code=status, payload=payload, headers=headers)
|
|
75
|
+
if status == 401:
|
|
76
|
+
return AuthenticationError(message, **kwargs)
|
|
77
|
+
if status == 403:
|
|
78
|
+
return ForbiddenError(message, **kwargs)
|
|
79
|
+
if status == 404:
|
|
80
|
+
return NotFoundError(message, **kwargs)
|
|
81
|
+
if status == 429:
|
|
82
|
+
return RateLimitError(message, retry_after=_retry_after(headers), **kwargs)
|
|
83
|
+
if status == 503:
|
|
84
|
+
return ServiceUnavailableError(message, **kwargs)
|
|
85
|
+
return APIError(message, **kwargs)
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def decode_body(text: str) -> Any:
|
|
89
|
+
"""Decode a successful response body (empty body -> ``None``)."""
|
|
90
|
+
if not text or not text.strip():
|
|
91
|
+
return None
|
|
92
|
+
try:
|
|
93
|
+
return _json.loads(text)
|
|
94
|
+
except ValueError:
|
|
95
|
+
raise APIError("Server returned a non-JSON response: %s" % text[:200], 200)
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
class _BaseClient:
|
|
99
|
+
"""Configuration, URL building and retry policy."""
|
|
100
|
+
|
|
101
|
+
def __init__(
|
|
102
|
+
self,
|
|
103
|
+
base_url: Optional[str] = None,
|
|
104
|
+
api_key: Optional[str] = None,
|
|
105
|
+
*,
|
|
106
|
+
timeout: float = 30.0,
|
|
107
|
+
max_retries: int = 2,
|
|
108
|
+
rate_limit: bool = True,
|
|
109
|
+
general_limit: int = 270,
|
|
110
|
+
create_limit: int = 9,
|
|
111
|
+
user_agent: Optional[str] = None,
|
|
112
|
+
) -> None:
|
|
113
|
+
base_url = base_url or os.environ.get(ENV_BASE_URL)
|
|
114
|
+
api_key = api_key or os.environ.get(ENV_API_KEY)
|
|
115
|
+
if not base_url:
|
|
116
|
+
raise ConfigurationError(
|
|
117
|
+
"base_url is required (pass base_url=... or set %s)." % ENV_BASE_URL
|
|
118
|
+
)
|
|
119
|
+
if not api_key:
|
|
120
|
+
raise ConfigurationError(
|
|
121
|
+
"api_key is required (pass api_key=... or set %s)." % ENV_API_KEY
|
|
122
|
+
)
|
|
123
|
+
self.base_url = normalize_base_url(base_url)
|
|
124
|
+
self._api_key = api_key.strip()
|
|
125
|
+
self.timeout = timeout
|
|
126
|
+
self.max_retries = max(int(max_retries), 0)
|
|
127
|
+
self._headers = {
|
|
128
|
+
"X-API-Key": self._api_key,
|
|
129
|
+
"Accept": "application/json",
|
|
130
|
+
"User-Agent": user_agent or "qubrixa-mail-python/%s" % __version__,
|
|
131
|
+
}
|
|
132
|
+
self._general_limiter = SlidingWindowLimiter(general_limit) if rate_limit else None
|
|
133
|
+
self._create_limiter = SlidingWindowLimiter(create_limit) if rate_limit else None
|
|
134
|
+
self._guard = StrikeGuard()
|
|
135
|
+
|
|
136
|
+
def __repr__(self) -> str:
|
|
137
|
+
return "%s(base_url=%r, api_key='%s...')" % (
|
|
138
|
+
type(self).__name__,
|
|
139
|
+
self.base_url,
|
|
140
|
+
self._api_key[:8],
|
|
141
|
+
)
|
|
142
|
+
|
|
143
|
+
# -- helpers ------------------------------------------------------------
|
|
144
|
+
def _url(self, path: str) -> str:
|
|
145
|
+
return self.base_url + path
|
|
146
|
+
|
|
147
|
+
def _timeouts(self, read: Optional[float] = None) -> Tuple[float, float]:
|
|
148
|
+
read = self.timeout if read is None else read
|
|
149
|
+
return (min(10.0, read), read)
|
|
150
|
+
|
|
151
|
+
@staticmethod
|
|
152
|
+
def _inbox_id(inbox: InboxRef) -> str:
|
|
153
|
+
value = inbox.id if isinstance(inbox, Inbox) else str(inbox)
|
|
154
|
+
if not value:
|
|
155
|
+
raise ValueError("inbox id must not be empty")
|
|
156
|
+
return quote(value, safe="@")
|
|
157
|
+
|
|
158
|
+
@staticmethod
|
|
159
|
+
def _message_id(message_id: Any) -> str:
|
|
160
|
+
value = getattr(message_id, "id", message_id)
|
|
161
|
+
return quote(str(value), safe="")
|
|
162
|
+
|
|
163
|
+
@staticmethod
|
|
164
|
+
def _create_body(
|
|
165
|
+
expires_in_seconds: Optional[int],
|
|
166
|
+
local_part: Optional[str],
|
|
167
|
+
webhook_url: Optional[str],
|
|
168
|
+
extra: Dict[str, Any],
|
|
169
|
+
) -> Dict[str, Any]:
|
|
170
|
+
body = {} # type: Dict[str, Any]
|
|
171
|
+
if expires_in_seconds is not None:
|
|
172
|
+
body["expires_in_seconds"] = int(expires_in_seconds)
|
|
173
|
+
if local_part is not None:
|
|
174
|
+
body["local_part"] = local_part
|
|
175
|
+
if webhook_url is not None:
|
|
176
|
+
body["webhook_url"] = webhook_url
|
|
177
|
+
body.update(extra)
|
|
178
|
+
return body
|
|
179
|
+
|
|
180
|
+
@staticmethod
|
|
181
|
+
def _check_wait(timeout: float) -> float:
|
|
182
|
+
if timeout <= 0:
|
|
183
|
+
raise ValueError("timeout must be > 0")
|
|
184
|
+
return float(timeout)
|
|
185
|
+
|
|
186
|
+
def _can_retry(self, method: str, attempt: int, retryable: bool) -> bool:
|
|
187
|
+
return retryable and method in IDEMPOTENT_METHODS and attempt < self.max_retries
|
|
188
|
+
|
|
189
|
+
@staticmethod
|
|
190
|
+
def _backoff(attempt: int, headers: Optional[Mapping[str, str]] = None) -> float:
|
|
191
|
+
hinted = _retry_after(headers) if headers else None
|
|
192
|
+
if hinted is not None:
|
|
193
|
+
return min(hinted, 30.0)
|
|
194
|
+
return min(0.5 * (2 ** attempt), 8.0) + random.uniform(0, 0.25)
|
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
"""Client-side protection against the server's rate limits and strike bans."""
|
|
2
|
+
|
|
3
|
+
import asyncio
|
|
4
|
+
import threading
|
|
5
|
+
import time
|
|
6
|
+
from collections import deque
|
|
7
|
+
from typing import Callable, Deque
|
|
8
|
+
|
|
9
|
+
from .exceptions import AbuseGuardError
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class SlidingWindowLimiter:
|
|
13
|
+
"""Thread-safe sliding-window limiter (``max_calls`` per ``period`` seconds)."""
|
|
14
|
+
|
|
15
|
+
def __init__(
|
|
16
|
+
self,
|
|
17
|
+
max_calls: int,
|
|
18
|
+
period: float = 60.0,
|
|
19
|
+
clock: Callable[[], float] = time.monotonic,
|
|
20
|
+
) -> None:
|
|
21
|
+
if max_calls < 1:
|
|
22
|
+
raise ValueError("max_calls must be >= 1")
|
|
23
|
+
self.max_calls = max_calls
|
|
24
|
+
self.period = period
|
|
25
|
+
self._clock = clock
|
|
26
|
+
self._calls = deque() # type: Deque[float]
|
|
27
|
+
self._lock = threading.Lock()
|
|
28
|
+
|
|
29
|
+
def try_acquire(self) -> float:
|
|
30
|
+
"""Reserve a slot. Returns 0.0 on success, otherwise seconds to wait."""
|
|
31
|
+
with self._lock:
|
|
32
|
+
now = self._clock()
|
|
33
|
+
while self._calls and now - self._calls[0] >= self.period:
|
|
34
|
+
self._calls.popleft()
|
|
35
|
+
if len(self._calls) < self.max_calls:
|
|
36
|
+
self._calls.append(now)
|
|
37
|
+
return 0.0
|
|
38
|
+
return max(self.period - (now - self._calls[0]), 0.001)
|
|
39
|
+
|
|
40
|
+
def acquire(self) -> None:
|
|
41
|
+
while True:
|
|
42
|
+
wait = self.try_acquire()
|
|
43
|
+
if wait <= 0:
|
|
44
|
+
return
|
|
45
|
+
time.sleep(wait)
|
|
46
|
+
|
|
47
|
+
async def acquire_async(self) -> None:
|
|
48
|
+
while True:
|
|
49
|
+
wait = self.try_acquire()
|
|
50
|
+
if wait <= 0:
|
|
51
|
+
return
|
|
52
|
+
await asyncio.sleep(wait)
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
class StrikeGuard:
|
|
56
|
+
"""Stops sending requests after several consecutive HTTP 429 responses.
|
|
57
|
+
|
|
58
|
+
The server bans a key after 5 consecutive violations inside 5 minutes; the
|
|
59
|
+
default here is to refuse locally after 3.
|
|
60
|
+
"""
|
|
61
|
+
|
|
62
|
+
def __init__(
|
|
63
|
+
self,
|
|
64
|
+
max_strikes: int = 3,
|
|
65
|
+
window: float = 300.0,
|
|
66
|
+
clock: Callable[[], float] = time.monotonic,
|
|
67
|
+
) -> None:
|
|
68
|
+
self.max_strikes = max_strikes
|
|
69
|
+
self.window = window
|
|
70
|
+
self._clock = clock
|
|
71
|
+
self._strikes = deque() # type: Deque[float]
|
|
72
|
+
self._lock = threading.Lock()
|
|
73
|
+
|
|
74
|
+
def _prune(self, now: float) -> None:
|
|
75
|
+
while self._strikes and now - self._strikes[0] >= self.window:
|
|
76
|
+
self._strikes.popleft()
|
|
77
|
+
|
|
78
|
+
def record_rate_limit(self) -> None:
|
|
79
|
+
with self._lock:
|
|
80
|
+
now = self._clock()
|
|
81
|
+
self._prune(now)
|
|
82
|
+
self._strikes.append(now)
|
|
83
|
+
|
|
84
|
+
def record_success(self) -> None:
|
|
85
|
+
with self._lock:
|
|
86
|
+
self._strikes.clear()
|
|
87
|
+
|
|
88
|
+
def check(self) -> None:
|
|
89
|
+
with self._lock:
|
|
90
|
+
now = self._clock()
|
|
91
|
+
self._prune(now)
|
|
92
|
+
if len(self._strikes) >= self.max_strikes:
|
|
93
|
+
retry_after = self.window - (now - self._strikes[0])
|
|
94
|
+
raise AbuseGuardError(
|
|
95
|
+
"%d consecutive rate-limit responses - pausing requests to avoid an "
|
|
96
|
+
"automatic key/IP suspension. Retry in %.0f seconds."
|
|
97
|
+
% (len(self._strikes), retry_after),
|
|
98
|
+
retry_after=retry_after,
|
|
99
|
+
)
|