movoice 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.
- movoice/__init__.py +50 -0
- movoice/_client.py +108 -0
- movoice/_http.py +281 -0
- movoice/_version.py +1 -0
- movoice/errors.py +248 -0
- movoice/pagination.py +75 -0
- movoice/py.typed +0 -0
- movoice/resources/__init__.py +22 -0
- movoice/resources/_base.py +23 -0
- movoice/resources/account.py +18 -0
- movoice/resources/agents.py +135 -0
- movoice/resources/appointments.py +188 -0
- movoice/resources/calls.py +111 -0
- movoice/resources/contacts.py +62 -0
- movoice/resources/memory.py +29 -0
- movoice/resources/messages.py +41 -0
- movoice/resources/numbers.py +30 -0
- movoice/types.py +345 -0
- movoice/webhooks.py +134 -0
- movoice-0.1.0.dist-info/METADATA +307 -0
- movoice-0.1.0.dist-info/RECORD +23 -0
- movoice-0.1.0.dist-info/WHEEL +4 -0
- movoice-0.1.0.dist-info/licenses/LICENSE +21 -0
movoice/__init__.py
ADDED
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
"""movoice: the official Python client for the Movoice AI API.
|
|
2
|
+
|
|
3
|
+
::
|
|
4
|
+
|
|
5
|
+
import movoice
|
|
6
|
+
|
|
7
|
+
client = movoice.Movoice() # reads MOVOICE_API_KEY
|
|
8
|
+
call = client.calls.create(agent_id="...", phone_number="+14155550123",
|
|
9
|
+
context_data={"leadId": "L-889"}, idempotency_key="call-L-889-1")
|
|
10
|
+
|
|
11
|
+
event = movoice.webhooks.verify(raw_body, headers, secret)
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
from . import webhooks
|
|
15
|
+
from ._client import Movoice
|
|
16
|
+
from ._version import __version__
|
|
17
|
+
from .errors import (
|
|
18
|
+
ApiError,
|
|
19
|
+
AuthenticationError,
|
|
20
|
+
ConflictError,
|
|
21
|
+
ConnectionError,
|
|
22
|
+
InsufficientBalanceError,
|
|
23
|
+
InvalidRequestError,
|
|
24
|
+
InvalidResponseError,
|
|
25
|
+
MovoiceError,
|
|
26
|
+
NotFoundError,
|
|
27
|
+
PermissionError,
|
|
28
|
+
RateLimitError,
|
|
29
|
+
WebhookVerificationError,
|
|
30
|
+
)
|
|
31
|
+
from .pagination import Page
|
|
32
|
+
|
|
33
|
+
__all__ = [
|
|
34
|
+
"Movoice",
|
|
35
|
+
"Page",
|
|
36
|
+
"webhooks",
|
|
37
|
+
"__version__",
|
|
38
|
+
"MovoiceError",
|
|
39
|
+
"AuthenticationError",
|
|
40
|
+
"PermissionError",
|
|
41
|
+
"InvalidRequestError",
|
|
42
|
+
"NotFoundError",
|
|
43
|
+
"ConflictError",
|
|
44
|
+
"InsufficientBalanceError",
|
|
45
|
+
"RateLimitError",
|
|
46
|
+
"ApiError",
|
|
47
|
+
"ConnectionError",
|
|
48
|
+
"InvalidResponseError",
|
|
49
|
+
"WebhookVerificationError",
|
|
50
|
+
]
|
movoice/_client.py
ADDED
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
"""The Movoice client.
|
|
2
|
+
|
|
3
|
+
::
|
|
4
|
+
|
|
5
|
+
from movoice import Movoice
|
|
6
|
+
|
|
7
|
+
client = Movoice() # reads MOVOICE_API_KEY
|
|
8
|
+
call = client.calls.create(agent_id=agent_id, phone_number="+14155550123")
|
|
9
|
+
|
|
10
|
+
Server-side only: a secret key can place calls and spend your balance.
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
from __future__ import annotations
|
|
14
|
+
|
|
15
|
+
import os
|
|
16
|
+
from types import ModuleType, TracebackType
|
|
17
|
+
from typing import Mapping, Optional, Type
|
|
18
|
+
|
|
19
|
+
import httpx
|
|
20
|
+
|
|
21
|
+
from . import webhooks as _webhooks
|
|
22
|
+
from ._http import DEFAULT_BASE_URL, DEFAULT_MAX_RETRIES, DEFAULT_TIMEOUT, HttpClient
|
|
23
|
+
from .resources import (
|
|
24
|
+
AccountResource,
|
|
25
|
+
Agents,
|
|
26
|
+
Appointments,
|
|
27
|
+
AvailabilityResource,
|
|
28
|
+
Calls,
|
|
29
|
+
Contacts,
|
|
30
|
+
Memory,
|
|
31
|
+
Messages,
|
|
32
|
+
Numbers,
|
|
33
|
+
)
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
class Movoice:
|
|
37
|
+
"""A client for the Movoice AI API.
|
|
38
|
+
|
|
39
|
+
:param api_key: your secret key, ``mv_live_...`` or ``mv_test_...``. Defaults to the
|
|
40
|
+
``MOVOICE_API_KEY`` environment variable. Publishable keys (``mv_pk_``) are refused.
|
|
41
|
+
:param base_url: defaults to ``https://app.movoice.ai``.
|
|
42
|
+
:param timeout: seconds before a single attempt is abandoned. Default 30.
|
|
43
|
+
:param max_retries: retries for requests that are safe to repeat. Default 2. A call or a
|
|
44
|
+
message is never retried unless you gave it an idempotency key.
|
|
45
|
+
:param default_headers: extra headers on every request. Cannot override ``Authorization``.
|
|
46
|
+
:param http_client: your own ``httpx.Client`` (proxies, custom transport, tests). The
|
|
47
|
+
client does not close one you pass in.
|
|
48
|
+
"""
|
|
49
|
+
|
|
50
|
+
def __init__(
|
|
51
|
+
self,
|
|
52
|
+
api_key: Optional[str] = None,
|
|
53
|
+
*,
|
|
54
|
+
base_url: str = DEFAULT_BASE_URL,
|
|
55
|
+
timeout: float = DEFAULT_TIMEOUT,
|
|
56
|
+
max_retries: int = DEFAULT_MAX_RETRIES,
|
|
57
|
+
default_headers: Optional[Mapping[str, str]] = None,
|
|
58
|
+
http_client: Optional[httpx.Client] = None,
|
|
59
|
+
) -> None:
|
|
60
|
+
if api_key is None:
|
|
61
|
+
api_key = os.environ.get("MOVOICE_API_KEY")
|
|
62
|
+
#: Escape hatch for endpoints this version does not wrap yet: ``client.http.request("GET", "/path")``.
|
|
63
|
+
self.http = HttpClient(
|
|
64
|
+
api_key or "",
|
|
65
|
+
base_url=base_url,
|
|
66
|
+
timeout=timeout,
|
|
67
|
+
max_retries=max_retries,
|
|
68
|
+
default_headers=default_headers,
|
|
69
|
+
http_client=http_client,
|
|
70
|
+
)
|
|
71
|
+
#: The voice agents that answer and place calls.
|
|
72
|
+
self.agents = Agents(self.http)
|
|
73
|
+
#: Place calls, hang them up, and read their history and transcripts.
|
|
74
|
+
self.calls = Calls(self.http)
|
|
75
|
+
#: Your address book.
|
|
76
|
+
self.contacts = Contacts(self.http)
|
|
77
|
+
#: Bookings on your agents' calendars.
|
|
78
|
+
self.appointments = Appointments(self.http)
|
|
79
|
+
#: Free times on an agent's calendar.
|
|
80
|
+
self.availability = AvailabilityResource(self.http)
|
|
81
|
+
#: The phone numbers on your account. Read only.
|
|
82
|
+
self.numbers = Numbers(self.http)
|
|
83
|
+
#: SMS and WhatsApp. These spend your balance.
|
|
84
|
+
self.messages = Messages(self.http)
|
|
85
|
+
#: What an agent remembers about a caller.
|
|
86
|
+
self.memory = Memory(self.http)
|
|
87
|
+
#: The account behind the key, including your Movoice Account ID.
|
|
88
|
+
self.account = AccountResource(self.http)
|
|
89
|
+
#: Verify a webhook delivery. Also usable without a client: ``movoice.webhooks.verify(...)``.
|
|
90
|
+
self.webhooks: ModuleType = _webhooks
|
|
91
|
+
|
|
92
|
+
def close(self) -> None:
|
|
93
|
+
"""Close the connection pool (only when the client created it)."""
|
|
94
|
+
self.http.close()
|
|
95
|
+
|
|
96
|
+
def __enter__(self) -> "Movoice":
|
|
97
|
+
return self
|
|
98
|
+
|
|
99
|
+
def __exit__(
|
|
100
|
+
self,
|
|
101
|
+
exc_type: Optional[Type[BaseException]],
|
|
102
|
+
exc: Optional[BaseException],
|
|
103
|
+
tb: Optional[TracebackType],
|
|
104
|
+
) -> None:
|
|
105
|
+
self.close()
|
|
106
|
+
|
|
107
|
+
def __repr__(self) -> str:
|
|
108
|
+
return f"Movoice(base_url={self.http.base_url!r})"
|
movoice/_http.py
ADDED
|
@@ -0,0 +1,281 @@
|
|
|
1
|
+
"""The transport: the key, the base URL, timeouts, retries and unwrapping the envelope.
|
|
2
|
+
|
|
3
|
+
Resource modules (agents, calls, ...) never touch httpx directly; they describe a request
|
|
4
|
+
and let this decide how it is made.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import builtins
|
|
10
|
+
import json
|
|
11
|
+
import random
|
|
12
|
+
import time
|
|
13
|
+
from typing import Any, Dict, Mapping, Optional
|
|
14
|
+
|
|
15
|
+
import httpx
|
|
16
|
+
|
|
17
|
+
from ._version import __version__
|
|
18
|
+
from .errors import (
|
|
19
|
+
ConnectionError,
|
|
20
|
+
InvalidResponseError,
|
|
21
|
+
MovoiceError,
|
|
22
|
+
RateLimitError,
|
|
23
|
+
error_from_response,
|
|
24
|
+
)
|
|
25
|
+
|
|
26
|
+
DEFAULT_BASE_URL = "https://app.movoice.ai"
|
|
27
|
+
API_ROOT = "/api/v1"
|
|
28
|
+
DEFAULT_TIMEOUT = 30.0
|
|
29
|
+
DEFAULT_MAX_RETRIES = 2
|
|
30
|
+
USER_AGENT = f"movoice-python/{__version__}"
|
|
31
|
+
|
|
32
|
+
_MISSING = object()
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def _sleep(seconds: float) -> None:
|
|
36
|
+
"""Indirection so tests can skip the wait between retries."""
|
|
37
|
+
time.sleep(seconds)
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
class HttpClient:
|
|
41
|
+
"""Makes one logical request, with retries where repeating it is safe.
|
|
42
|
+
|
|
43
|
+
Also the escape hatch for endpoints this version does not wrap yet::
|
|
44
|
+
|
|
45
|
+
data = client.http.request("GET", "/some/new/endpoint")
|
|
46
|
+
|
|
47
|
+
Paths are relative to ``/api/v1``.
|
|
48
|
+
"""
|
|
49
|
+
|
|
50
|
+
def __init__(
|
|
51
|
+
self,
|
|
52
|
+
api_key: str,
|
|
53
|
+
*,
|
|
54
|
+
base_url: Optional[str] = None,
|
|
55
|
+
timeout: float = DEFAULT_TIMEOUT,
|
|
56
|
+
max_retries: int = DEFAULT_MAX_RETRIES,
|
|
57
|
+
default_headers: Optional[Mapping[str, str]] = None,
|
|
58
|
+
http_client: Optional[httpx.Client] = None,
|
|
59
|
+
) -> None:
|
|
60
|
+
key = (api_key or "").strip()
|
|
61
|
+
if not key:
|
|
62
|
+
raise MovoiceError(
|
|
63
|
+
"No API key. Create one at https://app.movoice.ai/developer and pass it as "
|
|
64
|
+
"Movoice(api_key=...) or set MOVOICE_API_KEY.",
|
|
65
|
+
code="UNAUTHORIZED",
|
|
66
|
+
)
|
|
67
|
+
if key.startswith("mv_pk_"):
|
|
68
|
+
raise MovoiceError(
|
|
69
|
+
"That is a publishable key. Publishable keys (mv_pk_) only work with the chat widget "
|
|
70
|
+
"in a browser and cannot call the API. Use a secret key (mv_live_ or mv_test_) from "
|
|
71
|
+
"https://app.movoice.ai/developer, and keep it on your server.",
|
|
72
|
+
code="FORBIDDEN",
|
|
73
|
+
)
|
|
74
|
+
self._api_key = key
|
|
75
|
+
self.base_url = (base_url or DEFAULT_BASE_URL).rstrip("/")
|
|
76
|
+
self.timeout = timeout
|
|
77
|
+
self.max_retries = max(0, int(max_retries))
|
|
78
|
+
self._default_headers = dict(default_headers or {})
|
|
79
|
+
self._owns_client = http_client is None
|
|
80
|
+
self._client = http_client if http_client is not None else httpx.Client()
|
|
81
|
+
|
|
82
|
+
def close(self) -> None:
|
|
83
|
+
"""Close the connection pool, when this client created it."""
|
|
84
|
+
if self._owns_client:
|
|
85
|
+
self._client.close()
|
|
86
|
+
|
|
87
|
+
# ------------------------------------------------------------------
|
|
88
|
+
# Public entry points
|
|
89
|
+
# ------------------------------------------------------------------
|
|
90
|
+
|
|
91
|
+
def request(
|
|
92
|
+
self,
|
|
93
|
+
method: str,
|
|
94
|
+
path: str,
|
|
95
|
+
*,
|
|
96
|
+
query: Optional[Mapping[str, Any]] = None,
|
|
97
|
+
body: Any = _MISSING,
|
|
98
|
+
idempotency_key: Optional[str] = None,
|
|
99
|
+
accepts_idempotency_key: bool = False,
|
|
100
|
+
timeout: Optional[float] = None,
|
|
101
|
+
) -> Any:
|
|
102
|
+
"""Make a request and return the unwrapped ``data`` payload."""
|
|
103
|
+
return self._send(method, path, query, body, idempotency_key, accepts_idempotency_key, timeout, True)["data"]
|
|
104
|
+
|
|
105
|
+
def request_raw(
|
|
106
|
+
self,
|
|
107
|
+
method: str,
|
|
108
|
+
path: str,
|
|
109
|
+
*,
|
|
110
|
+
query: Optional[Mapping[str, Any]] = None,
|
|
111
|
+
timeout: Optional[float] = None,
|
|
112
|
+
) -> Any:
|
|
113
|
+
"""Return the body exactly as it arrived, with no envelope (only ``/memory/recall`` needs this)."""
|
|
114
|
+
return self._send(method, path, query, _MISSING, None, False, timeout, False)["data"]
|
|
115
|
+
|
|
116
|
+
def request_page(
|
|
117
|
+
self,
|
|
118
|
+
method: str,
|
|
119
|
+
path: str,
|
|
120
|
+
*,
|
|
121
|
+
query: Optional[Mapping[str, Any]] = None,
|
|
122
|
+
timeout: Optional[float] = None,
|
|
123
|
+
) -> Dict[str, Any]:
|
|
124
|
+
"""Make a request to a list endpoint and keep the pagination block."""
|
|
125
|
+
envelope = self._send(method, path, query, _MISSING, None, False, timeout, True)
|
|
126
|
+
data = envelope.get("data")
|
|
127
|
+
if not isinstance(data, list):
|
|
128
|
+
raise InvalidResponseError(
|
|
129
|
+
f"Expected a list from {path} but got {type(data).__name__}.",
|
|
130
|
+
code="INVALID_RESPONSE",
|
|
131
|
+
body=envelope,
|
|
132
|
+
)
|
|
133
|
+
meta = envelope.get("meta")
|
|
134
|
+
pagination = meta.get("pagination") if isinstance(meta, dict) else None
|
|
135
|
+
return {"data": data, "pagination": pagination}
|
|
136
|
+
|
|
137
|
+
# ------------------------------------------------------------------
|
|
138
|
+
# Internals
|
|
139
|
+
# ------------------------------------------------------------------
|
|
140
|
+
|
|
141
|
+
def _send(
|
|
142
|
+
self,
|
|
143
|
+
method: str,
|
|
144
|
+
path: str,
|
|
145
|
+
query: Optional[Mapping[str, Any]],
|
|
146
|
+
body: Any,
|
|
147
|
+
idempotency_key: Optional[str],
|
|
148
|
+
accepts_idempotency_key: bool,
|
|
149
|
+
timeout: Optional[float],
|
|
150
|
+
expect_envelope: bool,
|
|
151
|
+
) -> Dict[str, Any]:
|
|
152
|
+
method = method.upper()
|
|
153
|
+
_check_idempotency_key(method, path, idempotency_key, accepts_idempotency_key)
|
|
154
|
+
url = self.base_url + API_ROOT + path
|
|
155
|
+
params = _clean_query(query)
|
|
156
|
+
headers = self._headers(body is not _MISSING, idempotency_key if accepts_idempotency_key else None)
|
|
157
|
+
content = None if body is _MISSING else json.dumps(body, separators=(",", ":")).encode("utf-8")
|
|
158
|
+
# A GET can always be repeated. A write only with an Idempotency-Key the route honours:
|
|
159
|
+
# the server hands back the first answer for a repeat instead of acting again.
|
|
160
|
+
retryable_request = method == "GET" or (accepts_idempotency_key and idempotency_key is not None)
|
|
161
|
+
|
|
162
|
+
last_error: Optional[MovoiceError] = None
|
|
163
|
+
for attempt in range(self.max_retries + 1):
|
|
164
|
+
try:
|
|
165
|
+
response = self._client.request(
|
|
166
|
+
method,
|
|
167
|
+
url,
|
|
168
|
+
params=params,
|
|
169
|
+
headers=headers,
|
|
170
|
+
content=content,
|
|
171
|
+
timeout=self.timeout if timeout is None else timeout,
|
|
172
|
+
)
|
|
173
|
+
except httpx.TimeoutException as exc:
|
|
174
|
+
error: MovoiceError = ConnectionError(
|
|
175
|
+
"The request timed out. It may still have been processed: check before retrying "
|
|
176
|
+
"anything that spends money.",
|
|
177
|
+
code="TIMEOUT",
|
|
178
|
+
)
|
|
179
|
+
error.__cause__ = exc
|
|
180
|
+
except httpx.TransportError as exc:
|
|
181
|
+
error = ConnectionError(f"Could not reach the Movoice API: {exc}", code="CONNECTION_ERROR")
|
|
182
|
+
error.__cause__ = exc
|
|
183
|
+
else:
|
|
184
|
+
if 200 <= response.status_code < 300:
|
|
185
|
+
return self._parse_success(response, method, path, expect_envelope)
|
|
186
|
+
error = error_from_response(response.status_code, _read_json_safely(response), response.headers)
|
|
187
|
+
|
|
188
|
+
if not self._should_retry(error, retryable_request, attempt):
|
|
189
|
+
raise error
|
|
190
|
+
last_error = error
|
|
191
|
+
_sleep(_backoff_seconds(attempt, last_error))
|
|
192
|
+
|
|
193
|
+
# Unreachable: the last attempt always raises above.
|
|
194
|
+
raise last_error or ConnectionError("Request failed.", code="CONNECTION_ERROR") # pragma: no cover
|
|
195
|
+
|
|
196
|
+
def _headers(self, has_body: bool, idempotency_key: Optional[str]) -> Dict[str, str]:
|
|
197
|
+
reserved = {"accept", "authorization", "user-agent", "content-type", "idempotency-key"}
|
|
198
|
+
headers = {k: v for k, v in self._default_headers.items() if k.lower() not in reserved}
|
|
199
|
+
headers["Accept"] = "application/json"
|
|
200
|
+
headers["Authorization"] = f"Bearer {self._api_key}"
|
|
201
|
+
headers["User-Agent"] = USER_AGENT
|
|
202
|
+
if has_body:
|
|
203
|
+
headers["Content-Type"] = "application/json"
|
|
204
|
+
if idempotency_key is not None:
|
|
205
|
+
headers["Idempotency-Key"] = idempotency_key
|
|
206
|
+
return headers
|
|
207
|
+
|
|
208
|
+
def _parse_success(
|
|
209
|
+
self, response: httpx.Response, method: str, path: str, expect_envelope: bool
|
|
210
|
+
) -> Dict[str, Any]:
|
|
211
|
+
body = _read_json_safely(response)
|
|
212
|
+
# 204 No Content: DELETE answers this way and there is nothing to unwrap.
|
|
213
|
+
if response.status_code == 204 or body is None:
|
|
214
|
+
return {"data": None}
|
|
215
|
+
if not expect_envelope:
|
|
216
|
+
return {"data": body}
|
|
217
|
+
if not isinstance(body, dict) or "data" not in body:
|
|
218
|
+
raise InvalidResponseError(
|
|
219
|
+
f"{method} {path} returned {response.status_code} but not the expected response envelope.",
|
|
220
|
+
code="INVALID_RESPONSE",
|
|
221
|
+
status=response.status_code,
|
|
222
|
+
body=body,
|
|
223
|
+
)
|
|
224
|
+
return body
|
|
225
|
+
|
|
226
|
+
def _should_retry(self, error: MovoiceError, retryable_request: bool, attempt: int) -> bool:
|
|
227
|
+
if attempt >= self.max_retries:
|
|
228
|
+
return False
|
|
229
|
+
# Refused before doing any work, so repeating it cannot double-charge.
|
|
230
|
+
if error.code == "RATE_LIMITED":
|
|
231
|
+
return True
|
|
232
|
+
if not retryable_request:
|
|
233
|
+
return False
|
|
234
|
+
return error.is_retryable
|
|
235
|
+
|
|
236
|
+
|
|
237
|
+
def _check_idempotency_key(method: str, path: str, key: Optional[str], accepted: bool) -> None:
|
|
238
|
+
"""A key on a route that ignores it, or a key the server would refuse, fails before sending."""
|
|
239
|
+
if key is None:
|
|
240
|
+
return
|
|
241
|
+
if not accepted:
|
|
242
|
+
raise MovoiceError(
|
|
243
|
+
f"{method} {path} does not accept an Idempotency-Key, so the key would not protect "
|
|
244
|
+
"anything. Remove it.",
|
|
245
|
+
code="BAD_REQUEST",
|
|
246
|
+
)
|
|
247
|
+
if not isinstance(key, str) or not 8 <= len(key) <= 255:
|
|
248
|
+
raise MovoiceError("An Idempotency-Key must be 8 to 255 characters.", code="BAD_REQUEST")
|
|
249
|
+
|
|
250
|
+
|
|
251
|
+
def _clean_query(query: Optional[Mapping[str, Any]]) -> Dict[str, str]:
|
|
252
|
+
out: Dict[str, str] = {}
|
|
253
|
+
for key, value in (query or {}).items():
|
|
254
|
+
if value is None or value == "":
|
|
255
|
+
continue
|
|
256
|
+
if isinstance(value, builtins.bool):
|
|
257
|
+
out[key] = "true" if value else "false"
|
|
258
|
+
else:
|
|
259
|
+
out[key] = str(value)
|
|
260
|
+
return out
|
|
261
|
+
|
|
262
|
+
|
|
263
|
+
def _read_json_safely(response: httpx.Response) -> Any:
|
|
264
|
+
try:
|
|
265
|
+
text = response.text
|
|
266
|
+
except Exception: # pragma: no cover - undecodable body
|
|
267
|
+
return None
|
|
268
|
+
if not text:
|
|
269
|
+
return None
|
|
270
|
+
try:
|
|
271
|
+
return json.loads(text)
|
|
272
|
+
except ValueError:
|
|
273
|
+
# An HTML error page from a proxy, most likely. Keep it for the error body.
|
|
274
|
+
return {"error": {"message": text[:500]}}
|
|
275
|
+
|
|
276
|
+
|
|
277
|
+
def _backoff_seconds(attempt: int, error: Optional[MovoiceError]) -> float:
|
|
278
|
+
"""Exponential backoff with jitter, or the server's own Retry-After when it sent one."""
|
|
279
|
+
if isinstance(error, RateLimitError) and error.retry_after and error.retry_after > 0:
|
|
280
|
+
return float(min(error.retry_after, 60))
|
|
281
|
+
return min(0.5 * (2**attempt), 8.0) + random.random() * 0.25
|
movoice/_version.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
__version__ = "0.1.0"
|
movoice/errors.py
ADDED
|
@@ -0,0 +1,248 @@
|
|
|
1
|
+
"""One error type, whatever the API actually sent.
|
|
2
|
+
|
|
3
|
+
The API answers every failure in one shape::
|
|
4
|
+
|
|
5
|
+
{"success": false, "error": {"code": "NOT_FOUND", "message": "..."}}
|
|
6
|
+
|
|
7
|
+
It did not always: older deployments and proxies can still send an auth variant with no
|
|
8
|
+
``success`` field and lower-case codes, or a bare string ``error`` that is sometimes a reason
|
|
9
|
+
code and sometimes a sentence. This module reads all of them and always raises the same class
|
|
10
|
+
hierarchy, with ``code`` upper-cased so ``forbidden`` and ``FORBIDDEN`` both arrive as
|
|
11
|
+
``"FORBIDDEN"``. The raw values stay on ``raw_code`` and ``body``.
|
|
12
|
+
|
|
13
|
+
Two class names match Python built-ins on purpose, to match the other Movoice clients:
|
|
14
|
+
``movoice.PermissionError`` and ``movoice.ConnectionError``. Import them through the package
|
|
15
|
+
(``movoice.PermissionError``) or catch ``movoice.MovoiceError`` to catch everything.
|
|
16
|
+
"""
|
|
17
|
+
|
|
18
|
+
from __future__ import annotations
|
|
19
|
+
|
|
20
|
+
from typing import Any, Dict, List, Mapping, Optional
|
|
21
|
+
|
|
22
|
+
__all__ = [
|
|
23
|
+
"MovoiceError",
|
|
24
|
+
"AuthenticationError",
|
|
25
|
+
"PermissionError",
|
|
26
|
+
"InvalidRequestError",
|
|
27
|
+
"NotFoundError",
|
|
28
|
+
"ConflictError",
|
|
29
|
+
"InsufficientBalanceError",
|
|
30
|
+
"RateLimitError",
|
|
31
|
+
"ApiError",
|
|
32
|
+
"ConnectionError",
|
|
33
|
+
"InvalidResponseError",
|
|
34
|
+
"WebhookVerificationError",
|
|
35
|
+
"error_from_response",
|
|
36
|
+
]
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
class MovoiceError(Exception):
|
|
40
|
+
"""Base class for everything this library raises. Catch this to catch all of it."""
|
|
41
|
+
|
|
42
|
+
def __init__(
|
|
43
|
+
self,
|
|
44
|
+
message: str,
|
|
45
|
+
*,
|
|
46
|
+
code: str,
|
|
47
|
+
status: Optional[int] = None,
|
|
48
|
+
raw_code: Optional[str] = None,
|
|
49
|
+
details: Optional[Dict[str, Any]] = None,
|
|
50
|
+
body: Any = None,
|
|
51
|
+
) -> None:
|
|
52
|
+
super().__init__(message)
|
|
53
|
+
self.message = message
|
|
54
|
+
#: Normalised, upper-case code, e.g. ``"NOT_FOUND"``.
|
|
55
|
+
self.code = code
|
|
56
|
+
#: HTTP status, or ``None`` when the request never got a response.
|
|
57
|
+
self.status = status
|
|
58
|
+
#: The code exactly as the API sent it, before upper-casing.
|
|
59
|
+
self.raw_code = raw_code
|
|
60
|
+
self.details = details
|
|
61
|
+
#: The parsed response body, for debugging.
|
|
62
|
+
self.body = body
|
|
63
|
+
|
|
64
|
+
@property
|
|
65
|
+
def is_retryable(self) -> bool:
|
|
66
|
+
"""True when repeating the identical request could plausibly succeed.
|
|
67
|
+
|
|
68
|
+
This is about the error, not the request: the client never retries a POST that may
|
|
69
|
+
already have placed a call or sent a message, even when this is True.
|
|
70
|
+
"""
|
|
71
|
+
if self.code in ("RATE_LIMITED", "CONNECTION_ERROR", "TIMEOUT"):
|
|
72
|
+
return True
|
|
73
|
+
return self.status is not None and self.status >= 500
|
|
74
|
+
|
|
75
|
+
def __repr__(self) -> str:
|
|
76
|
+
return f"{type(self).__name__}(code={self.code!r}, status={self.status!r}, message={self.message!r})"
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
class AuthenticationError(MovoiceError):
|
|
80
|
+
"""401: the key is missing, malformed, expired or unknown."""
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
class PermissionError(MovoiceError): # noqa: A001 - named like the other Movoice clients
|
|
84
|
+
"""403: the key is real but is not allowed to do this. Usually a missing scope."""
|
|
85
|
+
|
|
86
|
+
@property
|
|
87
|
+
def required_scopes(self) -> Optional[List[str]]:
|
|
88
|
+
"""The scopes the endpoint required, when the API said."""
|
|
89
|
+
req = (self.details or {}).get("required")
|
|
90
|
+
return list(req) if isinstance(req, list) else None
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
class InvalidRequestError(MovoiceError):
|
|
94
|
+
"""400 / 422: the request was understood and rejected."""
|
|
95
|
+
|
|
96
|
+
@property
|
|
97
|
+
def field_errors(self) -> Optional[Dict[str, List[str]]]:
|
|
98
|
+
"""Per-field validation messages, e.g. ``{"phoneNumber": ["Invalid phone number"]}``."""
|
|
99
|
+
errs = (self.details or {}).get("errors")
|
|
100
|
+
return errs if isinstance(errs, dict) else None
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
class NotFoundError(MovoiceError):
|
|
104
|
+
"""404: no such thing on this account. Also returned for another account's ids."""
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
class ConflictError(MovoiceError):
|
|
108
|
+
"""409: the request conflicts with the current state."""
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
class InsufficientBalanceError(MovoiceError):
|
|
112
|
+
"""402: plan allowance and wallet are both empty. Top up, then retry."""
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
class RateLimitError(MovoiceError):
|
|
116
|
+
"""429: too many requests for this key."""
|
|
117
|
+
|
|
118
|
+
def __init__(self, message: str, *, retry_after: Optional[int] = None, **kwargs: Any) -> None:
|
|
119
|
+
super().__init__(message, **kwargs)
|
|
120
|
+
#: Seconds to wait, from the ``Retry-After`` header, when the API sent one.
|
|
121
|
+
self.retry_after = retry_after
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
class ApiError(MovoiceError):
|
|
125
|
+
"""5xx: the failure was on Movoice's side, not in your request."""
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
class ConnectionError(MovoiceError): # noqa: A001 - named like the other Movoice clients
|
|
129
|
+
"""The request never completed: DNS, TLS, socket or timeout.
|
|
130
|
+
|
|
131
|
+
A timeout can still have reached the server, so check before retrying anything that
|
|
132
|
+
spends money.
|
|
133
|
+
"""
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
class InvalidResponseError(MovoiceError):
|
|
137
|
+
"""A response came back, but not the JSON envelope the API is supposed to send."""
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
class WebhookVerificationError(MovoiceError):
|
|
141
|
+
"""A webhook delivery could not be proven to come from Movoice. Answer it with a 400."""
|
|
142
|
+
|
|
143
|
+
def __init__(self, message: str) -> None:
|
|
144
|
+
super().__init__(message, code="WEBHOOK_SIGNATURE_INVALID")
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
# ---------------------------------------------------------------------------
|
|
148
|
+
# Normalisation
|
|
149
|
+
# ---------------------------------------------------------------------------
|
|
150
|
+
|
|
151
|
+
_STATUS_FALLBACK = {
|
|
152
|
+
400: "The request was rejected.",
|
|
153
|
+
401: "The API key is missing, expired, or not recognised.",
|
|
154
|
+
402: "Your plan allowance and wallet balance are both exhausted.",
|
|
155
|
+
403: "This API key is not allowed to perform that action.",
|
|
156
|
+
404: "Not found on this account.",
|
|
157
|
+
409: "That conflicts with the current state.",
|
|
158
|
+
422: "The request could not be processed.",
|
|
159
|
+
429: "Rate limit exceeded for this API key.",
|
|
160
|
+
500: "Something failed on the Movoice side.",
|
|
161
|
+
503: "The service is temporarily unavailable.",
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
|
|
165
|
+
def _read_error_body(body: Any) -> Dict[str, Any]:
|
|
166
|
+
"""Pull ``raw_code``, ``message`` and ``details`` out of whichever envelope this is."""
|
|
167
|
+
if not isinstance(body, dict):
|
|
168
|
+
return {}
|
|
169
|
+
err = body.get("error")
|
|
170
|
+
if not err:
|
|
171
|
+
return {}
|
|
172
|
+
# Bare-string shape: ``{"error": "DAILY_SPEND_CAP", "message": "..."}`` carries the reason
|
|
173
|
+
# code in ``error``; with no sibling ``message`` the string is the message itself.
|
|
174
|
+
if isinstance(err, str):
|
|
175
|
+
sibling = body.get("message")
|
|
176
|
+
if isinstance(sibling, str):
|
|
177
|
+
return {"raw_code": err, "message": sibling}
|
|
178
|
+
return {"message": err}
|
|
179
|
+
if not isinstance(err, dict):
|
|
180
|
+
return {}
|
|
181
|
+
code = err.get("code")
|
|
182
|
+
message = err.get("message")
|
|
183
|
+
details = err.get("details")
|
|
184
|
+
return {
|
|
185
|
+
"raw_code": code if isinstance(code, str) else None,
|
|
186
|
+
"message": message if isinstance(message, str) else None,
|
|
187
|
+
"details": details if isinstance(details, dict) else None,
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
|
|
191
|
+
def _status_to_code(status: int) -> str:
|
|
192
|
+
return {
|
|
193
|
+
400: "BAD_REQUEST",
|
|
194
|
+
401: "UNAUTHORIZED",
|
|
195
|
+
402: "PAYMENT_REQUIRED",
|
|
196
|
+
403: "FORBIDDEN",
|
|
197
|
+
404: "NOT_FOUND",
|
|
198
|
+
409: "CONFLICT",
|
|
199
|
+
422: "UNPROCESSABLE_ENTITY",
|
|
200
|
+
429: "RATE_LIMITED",
|
|
201
|
+
503: "SERVICE_UNAVAILABLE",
|
|
202
|
+
}.get(status, "INTERNAL_ERROR" if status >= 500 else "BAD_REQUEST")
|
|
203
|
+
|
|
204
|
+
|
|
205
|
+
def _parse_retry_after(headers: Optional[Mapping[str, str]]) -> Optional[int]:
|
|
206
|
+
if headers is None:
|
|
207
|
+
return None
|
|
208
|
+
raw = headers.get("retry-after")
|
|
209
|
+
if raw is None:
|
|
210
|
+
return None
|
|
211
|
+
try:
|
|
212
|
+
return int(str(raw).strip())
|
|
213
|
+
except ValueError:
|
|
214
|
+
return None
|
|
215
|
+
|
|
216
|
+
|
|
217
|
+
def error_from_response(
|
|
218
|
+
status: int, body: Any, headers: Optional[Mapping[str, str]] = None
|
|
219
|
+
) -> MovoiceError:
|
|
220
|
+
"""Build the right error class from an HTTP response: status first, code second."""
|
|
221
|
+
parsed = _read_error_body(body)
|
|
222
|
+
raw_code = parsed.get("raw_code")
|
|
223
|
+
code = raw_code.upper() if raw_code else _status_to_code(status)
|
|
224
|
+
message = parsed.get("message") or _STATUS_FALLBACK.get(status) or f"Request failed with status {status}."
|
|
225
|
+
kwargs: Dict[str, Any] = {
|
|
226
|
+
"code": code,
|
|
227
|
+
"status": status,
|
|
228
|
+
"raw_code": raw_code,
|
|
229
|
+
"details": parsed.get("details"),
|
|
230
|
+
"body": body,
|
|
231
|
+
}
|
|
232
|
+
if status == 401:
|
|
233
|
+
return AuthenticationError(message, **kwargs)
|
|
234
|
+
if status == 402:
|
|
235
|
+
return InsufficientBalanceError(message, **kwargs)
|
|
236
|
+
if status == 403:
|
|
237
|
+
return PermissionError(message, **kwargs)
|
|
238
|
+
if status == 404:
|
|
239
|
+
return NotFoundError(message, **kwargs)
|
|
240
|
+
if status == 409:
|
|
241
|
+
return ConflictError(message, **kwargs)
|
|
242
|
+
if status in (400, 422):
|
|
243
|
+
return InvalidRequestError(message, **kwargs)
|
|
244
|
+
if status == 429:
|
|
245
|
+
return RateLimitError(message, retry_after=_parse_retry_after(headers), **kwargs)
|
|
246
|
+
if status >= 500:
|
|
247
|
+
return ApiError(message, **kwargs)
|
|
248
|
+
return MovoiceError(message, **kwargs)
|