msgine 1.0.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.
- msgine-1.0.0/.gitignore +18 -0
- msgine-1.0.0/PKG-INFO +155 -0
- msgine-1.0.0/README.md +139 -0
- msgine-1.0.0/pyproject.toml +42 -0
- msgine-1.0.0/src/msgine/__init__.py +16 -0
- msgine-1.0.0/src/msgine/_async.py +60 -0
- msgine-1.0.0/src/msgine/_core.py +155 -0
- msgine-1.0.0/src/msgine/_sync.py +60 -0
- msgine-1.0.0/src/msgine/_version.py +1 -0
- msgine-1.0.0/src/msgine/client.py +98 -0
- msgine-1.0.0/src/msgine/errors.py +32 -0
- msgine-1.0.0/src/msgine/py.typed +0 -0
- msgine-1.0.0/src/msgine/resources.py +551 -0
- msgine-1.0.0/src/msgine/webhooks.py +46 -0
- msgine-1.0.0/tests/conftest.py +56 -0
- msgine-1.0.0/tests/test_client.py +292 -0
- msgine-1.0.0/tests/test_webhooks.py +51 -0
msgine-1.0.0/.gitignore
ADDED
msgine-1.0.0/PKG-INFO
ADDED
|
@@ -0,0 +1,155 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: msgine
|
|
3
|
+
Version: 1.0.0
|
|
4
|
+
Summary: Python client for the MsGine messaging API
|
|
5
|
+
Project-URL: Documentation, https://docs.msgine.net
|
|
6
|
+
Classifier: Programming Language :: Python :: 3
|
|
7
|
+
Classifier: Typing :: Typed
|
|
8
|
+
Requires-Python: >=3.10
|
|
9
|
+
Requires-Dist: httpx<1,>=0.27
|
|
10
|
+
Provides-Extra: dev
|
|
11
|
+
Requires-Dist: mypy>=1.10; extra == 'dev'
|
|
12
|
+
Requires-Dist: pytest-asyncio>=0.23; extra == 'dev'
|
|
13
|
+
Requires-Dist: pytest>=8; extra == 'dev'
|
|
14
|
+
Requires-Dist: ruff>=0.5; extra == 'dev'
|
|
15
|
+
Description-Content-Type: text/markdown
|
|
16
|
+
|
|
17
|
+
# msgine
|
|
18
|
+
|
|
19
|
+
Python client for the MsGine messaging API: SMS, WhatsApp, email, push, workflows and webhooks.
|
|
20
|
+
|
|
21
|
+
Documentation: https://docs.msgine.net
|
|
22
|
+
|
|
23
|
+
## Install
|
|
24
|
+
|
|
25
|
+
```
|
|
26
|
+
pip install msgine
|
|
27
|
+
```
|
|
28
|
+
|
|
29
|
+
Requires Python 3.10 or newer. The only dependency is `httpx`.
|
|
30
|
+
|
|
31
|
+
## Quick start
|
|
32
|
+
|
|
33
|
+
```python
|
|
34
|
+
from msgine import MsGine
|
|
35
|
+
|
|
36
|
+
with MsGine("msg_<kid>_<secret>") as client:
|
|
37
|
+
message = client.sms.send(to="+256700000001", message="Your code is 4821")
|
|
38
|
+
print(message["id"], message["status"])
|
|
39
|
+
```
|
|
40
|
+
|
|
41
|
+
Async:
|
|
42
|
+
|
|
43
|
+
```python
|
|
44
|
+
import asyncio
|
|
45
|
+
from msgine import AsyncMsGine
|
|
46
|
+
|
|
47
|
+
async def main() -> None:
|
|
48
|
+
async with AsyncMsGine("msg_<kid>_<secret>") as client:
|
|
49
|
+
page = await client.sms.list(page=1, limit=20)
|
|
50
|
+
print(page.total, len(page.items))
|
|
51
|
+
|
|
52
|
+
asyncio.run(main())
|
|
53
|
+
```
|
|
54
|
+
|
|
55
|
+
Both clients expose the same resources and methods. Parameters are keyword-only and snake_case
|
|
56
|
+
(`scheduled_for`, `idempotency_key`, `from_`); they are sent under their API names. Nested data such as
|
|
57
|
+
`payload`, `definition` or `android` is sent as given. Responses are plain dicts with the API's camelCase
|
|
58
|
+
keys. List calls return `Page(items, total, page, pages)`.
|
|
59
|
+
|
|
60
|
+
## Configuration
|
|
61
|
+
|
|
62
|
+
```python
|
|
63
|
+
MsGine(
|
|
64
|
+
api_key,
|
|
65
|
+
signing_secret=None,
|
|
66
|
+
base_url="https://api.msgine.net/api/v1",
|
|
67
|
+
timeout=30.0,
|
|
68
|
+
max_retries=2,
|
|
69
|
+
http_client=None,
|
|
70
|
+
)
|
|
71
|
+
```
|
|
72
|
+
|
|
73
|
+
`http_client` takes an `httpx.Client` (`httpx.AsyncClient` for `AsyncMsGine`) to share a connection pool or
|
|
74
|
+
set proxies. A client you pass in is not closed by `close()`.
|
|
75
|
+
|
|
76
|
+
## Sending
|
|
77
|
+
|
|
78
|
+
```python
|
|
79
|
+
client.sms.send(to=["+256700000001", "+256700000002"], message="Hello", scheduled_for="2026-12-25T09:00:00Z")
|
|
80
|
+
|
|
81
|
+
client.whatsapp.send(to="+256700000001", template_id="order_update", template_language="en",
|
|
82
|
+
template_params=["A-1042"])
|
|
83
|
+
|
|
84
|
+
client.email.send(from_="hello@example.com", to="user@example.com", subject="Receipt", html="<p>Thanks</p>")
|
|
85
|
+
|
|
86
|
+
client.push.send(title="Order shipped", body="On its way", external_user_ids=["user-42"])
|
|
87
|
+
|
|
88
|
+
client.events.send(name="order.created", payload={"orderId": "A-1042"}, phone="+256700000001")
|
|
89
|
+
```
|
|
90
|
+
|
|
91
|
+
Email is transactional only. Recipients may be a string or a list. Every send carries an idempotency key:
|
|
92
|
+
yours (`idempotency_key=`) or a generated one that is reused across retries.
|
|
93
|
+
|
|
94
|
+
Other resources: `messages`, `webhooks`, `workflows` (`runs`, `launches`, `hooks`, `secrets`,
|
|
95
|
+
`messaging_policy`), `opt_outs`, `contact_fields`, `analytics`, `push.devices`, `push.config`.
|
|
96
|
+
|
|
97
|
+
## Webhooks
|
|
98
|
+
|
|
99
|
+
Verify the raw request body, not re-serialised JSON.
|
|
100
|
+
|
|
101
|
+
```python
|
|
102
|
+
from fastapi import FastAPI, HTTPException, Request
|
|
103
|
+
from msgine import WebhookVerificationError, verify_webhook
|
|
104
|
+
|
|
105
|
+
app = FastAPI()
|
|
106
|
+
|
|
107
|
+
@app.post("/msgine")
|
|
108
|
+
async def receive(request: Request) -> dict[str, bool]:
|
|
109
|
+
try:
|
|
110
|
+
event = verify_webhook(
|
|
111
|
+
await request.body(),
|
|
112
|
+
request.headers.get("x-msgine-signature"),
|
|
113
|
+
"whsec_...",
|
|
114
|
+
)
|
|
115
|
+
except WebhookVerificationError:
|
|
116
|
+
raise HTTPException(status_code=400)
|
|
117
|
+
print(event["event"], event["data"])
|
|
118
|
+
return {"ok": True}
|
|
119
|
+
```
|
|
120
|
+
|
|
121
|
+
Signatures older than 300 seconds are refused; change it with `tolerance=`. Several `v1` signatures are
|
|
122
|
+
accepted, so a rotated secret can overlap.
|
|
123
|
+
|
|
124
|
+
## Errors and retries
|
|
125
|
+
|
|
126
|
+
API errors raise `MsGineError` with `status`, `code`, `message`, `details`, `retry_after` and `body`.
|
|
127
|
+
Network failures and timeouts raise `MsGineConnectionError` (`status` 0, `code` `connection_error` or
|
|
128
|
+
`timeout`).
|
|
129
|
+
|
|
130
|
+
```python
|
|
131
|
+
from msgine import MsGineError
|
|
132
|
+
|
|
133
|
+
try:
|
|
134
|
+
client.sms.send(to="x", message="Hi")
|
|
135
|
+
except MsGineError as error:
|
|
136
|
+
print(error.status, error.code, error.details)
|
|
137
|
+
```
|
|
138
|
+
|
|
139
|
+
Up to `max_retries` retries (default 2). A 429 is always retried. Network errors, 408 and 5xx are retried
|
|
140
|
+
only for requests that are safe to repeat: GET, PUT and DELETE, and sends, which carry an idempotency key.
|
|
141
|
+
The wait follows `Retry-After` (1 to 60 seconds) or backs off exponentially from 1 second.
|
|
142
|
+
|
|
143
|
+
## Sandbox keys
|
|
144
|
+
|
|
145
|
+
A key created with the sandbox environment validates and records requests but sends nothing and charges
|
|
146
|
+
nothing. Use one in tests and CI.
|
|
147
|
+
|
|
148
|
+
## Request signing
|
|
149
|
+
|
|
150
|
+
Pass `signing_secret` to sign every request with `x-timestamp` and `x-signature` headers (HMAC-SHA256 of
|
|
151
|
+
method, path and query, timestamp and body hash). A fresh signature is computed for each attempt.
|
|
152
|
+
|
|
153
|
+
```python
|
|
154
|
+
client = MsGine("msg_<kid>_<secret>", signing_secret="sk_...")
|
|
155
|
+
```
|
msgine-1.0.0/README.md
ADDED
|
@@ -0,0 +1,139 @@
|
|
|
1
|
+
# msgine
|
|
2
|
+
|
|
3
|
+
Python client for the MsGine messaging API: SMS, WhatsApp, email, push, workflows and webhooks.
|
|
4
|
+
|
|
5
|
+
Documentation: https://docs.msgine.net
|
|
6
|
+
|
|
7
|
+
## Install
|
|
8
|
+
|
|
9
|
+
```
|
|
10
|
+
pip install msgine
|
|
11
|
+
```
|
|
12
|
+
|
|
13
|
+
Requires Python 3.10 or newer. The only dependency is `httpx`.
|
|
14
|
+
|
|
15
|
+
## Quick start
|
|
16
|
+
|
|
17
|
+
```python
|
|
18
|
+
from msgine import MsGine
|
|
19
|
+
|
|
20
|
+
with MsGine("msg_<kid>_<secret>") as client:
|
|
21
|
+
message = client.sms.send(to="+256700000001", message="Your code is 4821")
|
|
22
|
+
print(message["id"], message["status"])
|
|
23
|
+
```
|
|
24
|
+
|
|
25
|
+
Async:
|
|
26
|
+
|
|
27
|
+
```python
|
|
28
|
+
import asyncio
|
|
29
|
+
from msgine import AsyncMsGine
|
|
30
|
+
|
|
31
|
+
async def main() -> None:
|
|
32
|
+
async with AsyncMsGine("msg_<kid>_<secret>") as client:
|
|
33
|
+
page = await client.sms.list(page=1, limit=20)
|
|
34
|
+
print(page.total, len(page.items))
|
|
35
|
+
|
|
36
|
+
asyncio.run(main())
|
|
37
|
+
```
|
|
38
|
+
|
|
39
|
+
Both clients expose the same resources and methods. Parameters are keyword-only and snake_case
|
|
40
|
+
(`scheduled_for`, `idempotency_key`, `from_`); they are sent under their API names. Nested data such as
|
|
41
|
+
`payload`, `definition` or `android` is sent as given. Responses are plain dicts with the API's camelCase
|
|
42
|
+
keys. List calls return `Page(items, total, page, pages)`.
|
|
43
|
+
|
|
44
|
+
## Configuration
|
|
45
|
+
|
|
46
|
+
```python
|
|
47
|
+
MsGine(
|
|
48
|
+
api_key,
|
|
49
|
+
signing_secret=None,
|
|
50
|
+
base_url="https://api.msgine.net/api/v1",
|
|
51
|
+
timeout=30.0,
|
|
52
|
+
max_retries=2,
|
|
53
|
+
http_client=None,
|
|
54
|
+
)
|
|
55
|
+
```
|
|
56
|
+
|
|
57
|
+
`http_client` takes an `httpx.Client` (`httpx.AsyncClient` for `AsyncMsGine`) to share a connection pool or
|
|
58
|
+
set proxies. A client you pass in is not closed by `close()`.
|
|
59
|
+
|
|
60
|
+
## Sending
|
|
61
|
+
|
|
62
|
+
```python
|
|
63
|
+
client.sms.send(to=["+256700000001", "+256700000002"], message="Hello", scheduled_for="2026-12-25T09:00:00Z")
|
|
64
|
+
|
|
65
|
+
client.whatsapp.send(to="+256700000001", template_id="order_update", template_language="en",
|
|
66
|
+
template_params=["A-1042"])
|
|
67
|
+
|
|
68
|
+
client.email.send(from_="hello@example.com", to="user@example.com", subject="Receipt", html="<p>Thanks</p>")
|
|
69
|
+
|
|
70
|
+
client.push.send(title="Order shipped", body="On its way", external_user_ids=["user-42"])
|
|
71
|
+
|
|
72
|
+
client.events.send(name="order.created", payload={"orderId": "A-1042"}, phone="+256700000001")
|
|
73
|
+
```
|
|
74
|
+
|
|
75
|
+
Email is transactional only. Recipients may be a string or a list. Every send carries an idempotency key:
|
|
76
|
+
yours (`idempotency_key=`) or a generated one that is reused across retries.
|
|
77
|
+
|
|
78
|
+
Other resources: `messages`, `webhooks`, `workflows` (`runs`, `launches`, `hooks`, `secrets`,
|
|
79
|
+
`messaging_policy`), `opt_outs`, `contact_fields`, `analytics`, `push.devices`, `push.config`.
|
|
80
|
+
|
|
81
|
+
## Webhooks
|
|
82
|
+
|
|
83
|
+
Verify the raw request body, not re-serialised JSON.
|
|
84
|
+
|
|
85
|
+
```python
|
|
86
|
+
from fastapi import FastAPI, HTTPException, Request
|
|
87
|
+
from msgine import WebhookVerificationError, verify_webhook
|
|
88
|
+
|
|
89
|
+
app = FastAPI()
|
|
90
|
+
|
|
91
|
+
@app.post("/msgine")
|
|
92
|
+
async def receive(request: Request) -> dict[str, bool]:
|
|
93
|
+
try:
|
|
94
|
+
event = verify_webhook(
|
|
95
|
+
await request.body(),
|
|
96
|
+
request.headers.get("x-msgine-signature"),
|
|
97
|
+
"whsec_...",
|
|
98
|
+
)
|
|
99
|
+
except WebhookVerificationError:
|
|
100
|
+
raise HTTPException(status_code=400)
|
|
101
|
+
print(event["event"], event["data"])
|
|
102
|
+
return {"ok": True}
|
|
103
|
+
```
|
|
104
|
+
|
|
105
|
+
Signatures older than 300 seconds are refused; change it with `tolerance=`. Several `v1` signatures are
|
|
106
|
+
accepted, so a rotated secret can overlap.
|
|
107
|
+
|
|
108
|
+
## Errors and retries
|
|
109
|
+
|
|
110
|
+
API errors raise `MsGineError` with `status`, `code`, `message`, `details`, `retry_after` and `body`.
|
|
111
|
+
Network failures and timeouts raise `MsGineConnectionError` (`status` 0, `code` `connection_error` or
|
|
112
|
+
`timeout`).
|
|
113
|
+
|
|
114
|
+
```python
|
|
115
|
+
from msgine import MsGineError
|
|
116
|
+
|
|
117
|
+
try:
|
|
118
|
+
client.sms.send(to="x", message="Hi")
|
|
119
|
+
except MsGineError as error:
|
|
120
|
+
print(error.status, error.code, error.details)
|
|
121
|
+
```
|
|
122
|
+
|
|
123
|
+
Up to `max_retries` retries (default 2). A 429 is always retried. Network errors, 408 and 5xx are retried
|
|
124
|
+
only for requests that are safe to repeat: GET, PUT and DELETE, and sends, which carry an idempotency key.
|
|
125
|
+
The wait follows `Retry-After` (1 to 60 seconds) or backs off exponentially from 1 second.
|
|
126
|
+
|
|
127
|
+
## Sandbox keys
|
|
128
|
+
|
|
129
|
+
A key created with the sandbox environment validates and records requests but sends nothing and charges
|
|
130
|
+
nothing. Use one in tests and CI.
|
|
131
|
+
|
|
132
|
+
## Request signing
|
|
133
|
+
|
|
134
|
+
Pass `signing_secret` to sign every request with `x-timestamp` and `x-signature` headers (HMAC-SHA256 of
|
|
135
|
+
method, path and query, timestamp and body hash). A fresh signature is computed for each attempt.
|
|
136
|
+
|
|
137
|
+
```python
|
|
138
|
+
client = MsGine("msg_<kid>_<secret>", signing_secret="sk_...")
|
|
139
|
+
```
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["hatchling"]
|
|
3
|
+
build-backend = "hatchling.build"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "msgine"
|
|
7
|
+
version = "1.0.0"
|
|
8
|
+
description = "Python client for the MsGine messaging API"
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
requires-python = ">=3.10"
|
|
11
|
+
dependencies = ["httpx>=0.27,<1"]
|
|
12
|
+
classifiers = [
|
|
13
|
+
"Programming Language :: Python :: 3",
|
|
14
|
+
"Typing :: Typed",
|
|
15
|
+
]
|
|
16
|
+
|
|
17
|
+
[project.urls]
|
|
18
|
+
Documentation = "https://docs.msgine.net"
|
|
19
|
+
|
|
20
|
+
[project.optional-dependencies]
|
|
21
|
+
dev = ["pytest>=8", "pytest-asyncio>=0.23", "mypy>=1.10", "ruff>=0.5"]
|
|
22
|
+
|
|
23
|
+
[tool.hatch.build.targets.wheel]
|
|
24
|
+
packages = ["src/msgine"]
|
|
25
|
+
|
|
26
|
+
[tool.hatch.build.targets.sdist]
|
|
27
|
+
include = ["src/msgine", "tests", "README.md", "pyproject.toml"]
|
|
28
|
+
|
|
29
|
+
[tool.pytest.ini_options]
|
|
30
|
+
asyncio_mode = "auto"
|
|
31
|
+
testpaths = ["tests"]
|
|
32
|
+
|
|
33
|
+
[tool.mypy]
|
|
34
|
+
strict = true
|
|
35
|
+
python_version = "3.10"
|
|
36
|
+
|
|
37
|
+
[tool.ruff]
|
|
38
|
+
line-length = 110
|
|
39
|
+
target-version = "py310"
|
|
40
|
+
|
|
41
|
+
[tool.ruff.lint]
|
|
42
|
+
select = ["E", "F", "I", "UP", "B"]
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
from ._core import Page
|
|
2
|
+
from ._version import __version__
|
|
3
|
+
from .client import AsyncMsGine, MsGine
|
|
4
|
+
from .errors import MsGineConnectionError, MsGineError, WebhookVerificationError
|
|
5
|
+
from .webhooks import verify_webhook
|
|
6
|
+
|
|
7
|
+
__all__ = [
|
|
8
|
+
"AsyncMsGine",
|
|
9
|
+
"MsGine",
|
|
10
|
+
"MsGineConnectionError",
|
|
11
|
+
"MsGineError",
|
|
12
|
+
"Page",
|
|
13
|
+
"WebhookVerificationError",
|
|
14
|
+
"__version__",
|
|
15
|
+
"verify_webhook",
|
|
16
|
+
]
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from typing import Any
|
|
4
|
+
|
|
5
|
+
import httpx
|
|
6
|
+
|
|
7
|
+
from . import _core
|
|
8
|
+
from ._core import Config, Transform, backoff, encode_body, parse_body, retry_after_seconds, to_error
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
class AsyncTransport:
|
|
12
|
+
def __init__(self, config: Config, client: httpx.AsyncClient | None) -> None:
|
|
13
|
+
self._config = config
|
|
14
|
+
self._owns_client = client is None
|
|
15
|
+
self._client = client or httpx.AsyncClient()
|
|
16
|
+
|
|
17
|
+
async def aclose(self) -> None:
|
|
18
|
+
if self._owns_client:
|
|
19
|
+
await self._client.aclose()
|
|
20
|
+
|
|
21
|
+
async def request(
|
|
22
|
+
self,
|
|
23
|
+
method: str,
|
|
24
|
+
path: str,
|
|
25
|
+
*,
|
|
26
|
+
query: dict[str, Any] | None = None,
|
|
27
|
+
body: Any = None,
|
|
28
|
+
idempotent: bool = False,
|
|
29
|
+
transform: Transform = None,
|
|
30
|
+
) -> Any:
|
|
31
|
+
config = self._config
|
|
32
|
+
url = config.url(path, query)
|
|
33
|
+
content = encode_body(body)
|
|
34
|
+
repeatable = _core.safe_to_repeat(method, idempotent)
|
|
35
|
+
attempt = 0
|
|
36
|
+
while True:
|
|
37
|
+
try:
|
|
38
|
+
response = await self._client.request(
|
|
39
|
+
method,
|
|
40
|
+
url,
|
|
41
|
+
content=content,
|
|
42
|
+
headers=config.headers(method, url, content),
|
|
43
|
+
timeout=config.timeout,
|
|
44
|
+
)
|
|
45
|
+
except httpx.HTTPError as error:
|
|
46
|
+
if repeatable and attempt < config.max_retries:
|
|
47
|
+
await _core.asleep(backoff(attempt))
|
|
48
|
+
attempt += 1
|
|
49
|
+
continue
|
|
50
|
+
raise _core.connection_error(error, config.timeout) from error
|
|
51
|
+
|
|
52
|
+
if response.is_success:
|
|
53
|
+
result = parse_body(response)
|
|
54
|
+
return transform(result) if transform else result
|
|
55
|
+
|
|
56
|
+
retry_after = retry_after_seconds(response.headers.get("retry-after"))
|
|
57
|
+
if not config.should_retry(attempt, response.status_code, repeatable):
|
|
58
|
+
raise to_error(response, retry_after)
|
|
59
|
+
await _core.asleep(retry_after if retry_after is not None else backoff(attempt))
|
|
60
|
+
attempt += 1
|
|
@@ -0,0 +1,155 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import asyncio
|
|
4
|
+
import hashlib
|
|
5
|
+
import hmac
|
|
6
|
+
import json
|
|
7
|
+
import random
|
|
8
|
+
import time
|
|
9
|
+
from collections.abc import Callable
|
|
10
|
+
from dataclasses import dataclass
|
|
11
|
+
from email.utils import parsedate_to_datetime
|
|
12
|
+
from typing import Any
|
|
13
|
+
from urllib.parse import quote, urlencode, urlsplit
|
|
14
|
+
|
|
15
|
+
import httpx
|
|
16
|
+
|
|
17
|
+
from ._version import __version__
|
|
18
|
+
from .errors import MsGineConnectionError, MsGineError
|
|
19
|
+
|
|
20
|
+
DEFAULT_BASE_URL = "https://api.msgine.net/api/v1"
|
|
21
|
+
|
|
22
|
+
Transform = Callable[[Any], Any] | None
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
@dataclass(frozen=True)
|
|
26
|
+
class Page:
|
|
27
|
+
items: list[Any]
|
|
28
|
+
total: Any
|
|
29
|
+
page: Any
|
|
30
|
+
pages: Any
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def sleep(seconds: float) -> None:
|
|
34
|
+
time.sleep(seconds)
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
async def asleep(seconds: float) -> None:
|
|
38
|
+
await asyncio.sleep(seconds)
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def backoff(attempt: int) -> float:
|
|
42
|
+
return float(min(1.0 * 2**attempt, 8.0) + random.random() * 0.25)
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def retry_after_seconds(header: str | None) -> float | None:
|
|
46
|
+
if not header:
|
|
47
|
+
return None
|
|
48
|
+
try:
|
|
49
|
+
return min(max(float(header), 1.0), 60.0)
|
|
50
|
+
except ValueError:
|
|
51
|
+
pass
|
|
52
|
+
try:
|
|
53
|
+
date = parsedate_to_datetime(header)
|
|
54
|
+
except (TypeError, ValueError):
|
|
55
|
+
return None
|
|
56
|
+
return min(max(date.timestamp() - time.time(), 1.0), 60.0)
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def parse_body(response: httpx.Response) -> Any:
|
|
60
|
+
return response.json() if response.content else None
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def to_error(response: httpx.Response, retry_after: float | None) -> MsGineError:
|
|
64
|
+
text = response.text
|
|
65
|
+
body: Any
|
|
66
|
+
try:
|
|
67
|
+
body = json.loads(text) if text else {}
|
|
68
|
+
except ValueError:
|
|
69
|
+
body = {"message": text}
|
|
70
|
+
if not isinstance(body, dict):
|
|
71
|
+
body = {"message": text}
|
|
72
|
+
message = body.get("message")
|
|
73
|
+
code = body.get("error")
|
|
74
|
+
details = body.get("details")
|
|
75
|
+
return MsGineError(
|
|
76
|
+
message if isinstance(message, str) and message else f"HTTP {response.status_code}",
|
|
77
|
+
status=response.status_code,
|
|
78
|
+
code=code if isinstance(code, str) else "http_error",
|
|
79
|
+
details=details if isinstance(details, list) else None,
|
|
80
|
+
retry_after=retry_after,
|
|
81
|
+
body=body,
|
|
82
|
+
)
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def connection_error(error: httpx.HTTPError, timeout: float) -> MsGineConnectionError:
|
|
86
|
+
if isinstance(error, httpx.TimeoutException):
|
|
87
|
+
return MsGineConnectionError(f"Request timed out after {timeout} s", "timeout")
|
|
88
|
+
return MsGineConnectionError(f"Could not reach MsGine: {error}", "connection_error")
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
class Config:
|
|
92
|
+
def __init__(
|
|
93
|
+
self,
|
|
94
|
+
api_key: str,
|
|
95
|
+
signing_secret: str | None,
|
|
96
|
+
base_url: str,
|
|
97
|
+
timeout: float,
|
|
98
|
+
max_retries: int,
|
|
99
|
+
) -> None:
|
|
100
|
+
if not api_key:
|
|
101
|
+
raise ValueError("MsGine: api_key is required")
|
|
102
|
+
self.api_key = api_key
|
|
103
|
+
self.signing_secret = signing_secret
|
|
104
|
+
self.base_url = base_url.rstrip("/")
|
|
105
|
+
self.timeout = timeout
|
|
106
|
+
self.max_retries = max_retries
|
|
107
|
+
|
|
108
|
+
def url(self, path: str, query: dict[str, Any] | None) -> str:
|
|
109
|
+
pairs = [(key, _query_value(value)) for key, value in (query or {}).items() if value is not None]
|
|
110
|
+
return self.base_url + path + (f"?{urlencode(pairs)}" if pairs else "")
|
|
111
|
+
|
|
112
|
+
def headers(self, method: str, url: str, content: bytes | None) -> dict[str, str]:
|
|
113
|
+
headers = {
|
|
114
|
+
"accept": "application/json",
|
|
115
|
+
"user-agent": f"msgine-python/{__version__}",
|
|
116
|
+
"x-api-key": self.api_key,
|
|
117
|
+
}
|
|
118
|
+
if content is not None:
|
|
119
|
+
headers["content-type"] = "application/json"
|
|
120
|
+
if self.signing_secret:
|
|
121
|
+
parts = urlsplit(url)
|
|
122
|
+
target = parts.path + (f"?{parts.query}" if parts.query else "")
|
|
123
|
+
timestamp = str(int(time.time()))
|
|
124
|
+
body_hash = hashlib.sha256(content or b"").hexdigest()
|
|
125
|
+
message = f"{method}{target}{timestamp}{body_hash}"
|
|
126
|
+
headers["x-timestamp"] = timestamp
|
|
127
|
+
headers["x-signature"] = hmac.new(
|
|
128
|
+
self.signing_secret.encode(), message.encode(), hashlib.sha256
|
|
129
|
+
).hexdigest()
|
|
130
|
+
return headers
|
|
131
|
+
|
|
132
|
+
def should_retry(self, attempt: int, status: int, safe_to_repeat: bool) -> bool:
|
|
133
|
+
return attempt < self.max_retries and (
|
|
134
|
+
status == 429 or (safe_to_repeat and (status == 408 or status >= 500))
|
|
135
|
+
)
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
def _query_value(value: Any) -> str:
|
|
139
|
+
if isinstance(value, bool):
|
|
140
|
+
return "true" if value else "false"
|
|
141
|
+
return str(value)
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
def encode_body(body: Any) -> bytes | None:
|
|
145
|
+
if body is None:
|
|
146
|
+
return None
|
|
147
|
+
return json.dumps(body, separators=(",", ":"), ensure_ascii=False).encode("utf-8")
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
def safe_to_repeat(method: str, idempotent: bool) -> bool:
|
|
151
|
+
return method not in ("POST", "PATCH") or idempotent
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
def path_id(value: str) -> str:
|
|
155
|
+
return quote(value, safe="")
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from typing import Any
|
|
4
|
+
|
|
5
|
+
import httpx
|
|
6
|
+
|
|
7
|
+
from . import _core
|
|
8
|
+
from ._core import Config, Transform, backoff, encode_body, parse_body, retry_after_seconds, to_error
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
class SyncTransport:
|
|
12
|
+
def __init__(self, config: Config, client: httpx.Client | None) -> None:
|
|
13
|
+
self._config = config
|
|
14
|
+
self._owns_client = client is None
|
|
15
|
+
self._client = client or httpx.Client()
|
|
16
|
+
|
|
17
|
+
def close(self) -> None:
|
|
18
|
+
if self._owns_client:
|
|
19
|
+
self._client.close()
|
|
20
|
+
|
|
21
|
+
def request(
|
|
22
|
+
self,
|
|
23
|
+
method: str,
|
|
24
|
+
path: str,
|
|
25
|
+
*,
|
|
26
|
+
query: dict[str, Any] | None = None,
|
|
27
|
+
body: Any = None,
|
|
28
|
+
idempotent: bool = False,
|
|
29
|
+
transform: Transform = None,
|
|
30
|
+
) -> Any:
|
|
31
|
+
config = self._config
|
|
32
|
+
url = config.url(path, query)
|
|
33
|
+
content = encode_body(body)
|
|
34
|
+
repeatable = _core.safe_to_repeat(method, idempotent)
|
|
35
|
+
attempt = 0
|
|
36
|
+
while True:
|
|
37
|
+
try:
|
|
38
|
+
response = self._client.request(
|
|
39
|
+
method,
|
|
40
|
+
url,
|
|
41
|
+
content=content,
|
|
42
|
+
headers=config.headers(method, url, content),
|
|
43
|
+
timeout=config.timeout,
|
|
44
|
+
)
|
|
45
|
+
except httpx.HTTPError as error:
|
|
46
|
+
if repeatable and attempt < config.max_retries:
|
|
47
|
+
_core.sleep(backoff(attempt))
|
|
48
|
+
attempt += 1
|
|
49
|
+
continue
|
|
50
|
+
raise _core.connection_error(error, config.timeout) from error
|
|
51
|
+
|
|
52
|
+
if response.is_success:
|
|
53
|
+
result = parse_body(response)
|
|
54
|
+
return transform(result) if transform else result
|
|
55
|
+
|
|
56
|
+
retry_after = retry_after_seconds(response.headers.get("retry-after"))
|
|
57
|
+
if not config.should_retry(attempt, response.status_code, repeatable):
|
|
58
|
+
raise to_error(response, retry_after)
|
|
59
|
+
_core.sleep(retry_after if retry_after is not None else backoff(attempt))
|
|
60
|
+
attempt += 1
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
__version__ = "1.0.0"
|