recvd 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.
- recvd/__init__.py +8 -0
- recvd/client.py +397 -0
- recvd/errors.py +29 -0
- recvd/metering.py +392 -0
- recvd/py.typed +0 -0
- recvd/types.py +600 -0
- recvd/webhooks.py +49 -0
- recvd-0.1.0.dist-info/METADATA +105 -0
- recvd-0.1.0.dist-info/RECORD +12 -0
- recvd-0.1.0.dist-info/WHEEL +5 -0
- recvd-0.1.0.dist-info/licenses/LICENSE +21 -0
- recvd-0.1.0.dist-info/top_level.txt +1 -0
recvd/__init__.py
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
"""The Recvd API for Python. https://recvd.co/docs"""
|
|
2
|
+
from .client import VERSION as __version__
|
|
3
|
+
from .client import Recvd
|
|
4
|
+
from .errors import RecvdConnectionError, RecvdError, RecvdSignatureError
|
|
5
|
+
from .metering import Metered, TokenUsage, usage_of
|
|
6
|
+
from .webhooks import sign_webhook, verify_webhook
|
|
7
|
+
|
|
8
|
+
__all__ = ["Metered", "Recvd", "RecvdConnectionError", "RecvdError", "RecvdSignatureError", "TokenUsage", "__version__", "sign_webhook", "usage_of", "verify_webhook"]
|
recvd/client.py
ADDED
|
@@ -0,0 +1,397 @@
|
|
|
1
|
+
"""The Recvd API for one business, with the key of that business.
|
|
2
|
+
|
|
3
|
+
Standard library only. Keep the key on a server: a key in a page or an app is public.
|
|
4
|
+
"""
|
|
5
|
+
from __future__ import annotations
|
|
6
|
+
|
|
7
|
+
import http.client
|
|
8
|
+
import json
|
|
9
|
+
import time
|
|
10
|
+
import urllib.error
|
|
11
|
+
import urllib.parse
|
|
12
|
+
import urllib.request
|
|
13
|
+
import uuid
|
|
14
|
+
from typing import TYPE_CHECKING, Any, Callable, Dict, Iterator, List, Optional, Tuple, TypedDict
|
|
15
|
+
|
|
16
|
+
from .errors import RecvdConnectionError, RecvdError
|
|
17
|
+
from .metering import Metered
|
|
18
|
+
|
|
19
|
+
if TYPE_CHECKING:
|
|
20
|
+
from . import types as T
|
|
21
|
+
|
|
22
|
+
VERSION = "0.1.0"
|
|
23
|
+
#: What sends a request: (method, url, headers, body, timeout) -> (status, body). Swap it in tests.
|
|
24
|
+
Transport = Callable[[str, str, Dict[str, str], Optional[bytes], float], Tuple[int, bytes]]
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
class Listing(TypedDict):
|
|
28
|
+
"""A list answer. Ask for the next page with ``starting_after`` set to the id of the last item."""
|
|
29
|
+
|
|
30
|
+
object: str
|
|
31
|
+
data: List[Any]
|
|
32
|
+
has_more: bool
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
class _NoRedirect(urllib.request.HTTPRedirectHandler):
|
|
36
|
+
"""A redirect is not followed: the key goes to the address it was given for and nowhere else."""
|
|
37
|
+
|
|
38
|
+
def redirect_request(self, *args: Any, **kwargs: Any) -> None:
|
|
39
|
+
return None
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
_opener = urllib.request.build_opener(_NoRedirect)
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def _urllib(method: str, url: str, headers: Dict[str, str], body: Optional[bytes], timeout: float) -> Tuple[int, bytes]:
|
|
46
|
+
request = urllib.request.Request(url, data=body, headers=headers, method=method)
|
|
47
|
+
try:
|
|
48
|
+
with _opener.open(request, timeout=timeout) as response: # noqa: S310 (the address is the caller's own base_url)
|
|
49
|
+
return response.status, response.read()
|
|
50
|
+
except urllib.error.HTTPError as error:
|
|
51
|
+
with error:
|
|
52
|
+
return error.code, error.read()
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def _keyed(body: Dict[str, Any]) -> Dict[str, Any]:
|
|
56
|
+
"""A write that takes an idempotency key always carries one: the caller's, or one made here, the same on every retry."""
|
|
57
|
+
return body if body.get("idempotency_key") else {**body, "idempotency_key": str(uuid.uuid4())}
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def _clean(values: Dict[str, Any]) -> Dict[str, Any]:
|
|
61
|
+
return {name: value for name, value in values.items() if value is not None}
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
class _Group:
|
|
65
|
+
def __init__(self, client: "Recvd") -> None:
|
|
66
|
+
self._c = client
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
class Products(_Group):
|
|
70
|
+
def list(self, **params: Any) -> Listing:
|
|
71
|
+
"""Every product, newest first. ``limit``, ``starting_after``."""
|
|
72
|
+
return self._c._get("/products", params)
|
|
73
|
+
|
|
74
|
+
def all(self, **params: Any) -> Iterator["T.Product"]:
|
|
75
|
+
return self._c._all("/products", params)
|
|
76
|
+
|
|
77
|
+
def get(self, id: str) -> "T.Product":
|
|
78
|
+
return self._c._get(f"/products/{_seg(id)}")
|
|
79
|
+
|
|
80
|
+
def create(self, **body: Any) -> "T.Product":
|
|
81
|
+
"""Not on sale until a person at Recvd has approved it; in a test business it is on sale at once."""
|
|
82
|
+
return self._c._post("/products", body)
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
class Sales(_Group):
|
|
86
|
+
def list(self, **params: Any) -> Listing:
|
|
87
|
+
"""Paid, refunded and disputed sales, newest first. ``reference``, ``buyer_email``, ``limit``, ``starting_after``."""
|
|
88
|
+
return self._c._get("/sales", params)
|
|
89
|
+
|
|
90
|
+
def all(self, **params: Any) -> Iterator["T.Sale"]:
|
|
91
|
+
return self._c._all("/sales", params)
|
|
92
|
+
|
|
93
|
+
def get(self, id: str) -> "T.Sale":
|
|
94
|
+
return self._c._get(f"/sales/{_seg(id)}")
|
|
95
|
+
|
|
96
|
+
def refund(self, id: str, amount: Optional[int] = None) -> "T.Sale":
|
|
97
|
+
"""All of it, or with ``amount`` a part. It cannot be undone."""
|
|
98
|
+
return self._c._post(f"/sales/{_seg(id)}/refund", _clean({"amount": amount}))
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
class Subscriptions(_Group):
|
|
102
|
+
def list(self, **params: Any) -> Listing:
|
|
103
|
+
return self._c._get("/subscriptions", params)
|
|
104
|
+
|
|
105
|
+
def all(self, **params: Any) -> Iterator["T.Subscription"]:
|
|
106
|
+
return self._c._all("/subscriptions", params)
|
|
107
|
+
|
|
108
|
+
def get(self, id: str) -> "T.Subscription":
|
|
109
|
+
return self._c._get(f"/subscriptions/{_seg(id)}")
|
|
110
|
+
|
|
111
|
+
def cancel(self, id: str, reason: Optional[str] = None, note: Optional[str] = None) -> "T.Subscription":
|
|
112
|
+
"""Ends when the period already paid for is over. It cannot be undone."""
|
|
113
|
+
return self._c._post(f"/subscriptions/{_seg(id)}/cancel", _clean({"reason": reason, "note": note}))
|
|
114
|
+
|
|
115
|
+
def change_plan(self, id: str, product_id: str) -> "T.Subscription":
|
|
116
|
+
return self._c._post(f"/subscriptions/{_seg(id)}/change", {"product_id": product_id})
|
|
117
|
+
|
|
118
|
+
def change_seats(self, id: str, seats: int) -> "T.Subscription":
|
|
119
|
+
return self._c._post(f"/subscriptions/{_seg(id)}/seats", {"seats": seats})
|
|
120
|
+
|
|
121
|
+
def pause(self, id: str, months: int) -> "T.Subscription":
|
|
122
|
+
return self._c._post(f"/subscriptions/{_seg(id)}/pause", {"months": months})
|
|
123
|
+
|
|
124
|
+
def resume(self, id: str) -> "T.Subscription":
|
|
125
|
+
return self._c._post(f"/subscriptions/{_seg(id)}/resume")
|
|
126
|
+
|
|
127
|
+
def charge_usage(self, id: str, **body: Any) -> "T.UsageCharge":
|
|
128
|
+
"""Charges the subscriber at once. ``quantity``, and your own ``idempotency_key`` where you can; ``memo``, ``meter``."""
|
|
129
|
+
return self._c._post(f"/subscriptions/{_seg(id)}/usage", _keyed(body), repeatable=True)
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
class UsageCharges(_Group):
|
|
133
|
+
def list(self, **params: Any) -> Listing:
|
|
134
|
+
return self._c._get("/usage_charges", params)
|
|
135
|
+
|
|
136
|
+
def all(self, **params: Any) -> Iterator["T.UsageCharge"]:
|
|
137
|
+
return self._c._all("/usage_charges", params)
|
|
138
|
+
|
|
139
|
+
def get(self, id: str) -> "T.UsageCharge":
|
|
140
|
+
return self._c._get(f"/usage_charges/{_seg(id)}")
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
class UsageEvents(_Group):
|
|
144
|
+
def list(self, **params: Any) -> Listing:
|
|
145
|
+
return self._c._get("/usage_events", params)
|
|
146
|
+
|
|
147
|
+
def all(self, **params: Any) -> Iterator["T.UsageEvent"]:
|
|
148
|
+
return self._c._all("/usage_events", params)
|
|
149
|
+
|
|
150
|
+
def get(self, id: str) -> "T.UsageEvent":
|
|
151
|
+
return self._c._get(f"/usage_events/{_seg(id)}")
|
|
152
|
+
|
|
153
|
+
def record(self, **event: Any) -> "T.UsageEvent":
|
|
154
|
+
"""One usage event: ``quantity`` and who used it (``subscription_id``, ``reference``, ``buyer_email`` or ``task_id``).
|
|
155
|
+
|
|
156
|
+
Give your own ``idempotency_key`` where you can, so the same usage reported twice counts once.
|
|
157
|
+
"""
|
|
158
|
+
return self._c._post("/usage_events", _keyed(event), repeatable=True)
|
|
159
|
+
|
|
160
|
+
def record_many(self, events: List[Dict[str, Any]]) -> "T.UsageEventResults":
|
|
161
|
+
"""Up to 100 events in one request. Each is counted or refused by itself: look at each answer's ``object``."""
|
|
162
|
+
return self._c._post("/usage_events", {"events": [_keyed(event) for event in events]}, repeatable=True)
|
|
163
|
+
|
|
164
|
+
|
|
165
|
+
class Tasks(_Group):
|
|
166
|
+
def list(self, **params: Any) -> Listing:
|
|
167
|
+
return self._c._get("/tasks", params)
|
|
168
|
+
|
|
169
|
+
def all(self, **params: Any) -> Iterator["T.Task"]:
|
|
170
|
+
return self._c._all("/tasks", params)
|
|
171
|
+
|
|
172
|
+
def get(self, id: str) -> "T.Task":
|
|
173
|
+
return self._c._get(f"/tasks/{_seg(id)}")
|
|
174
|
+
|
|
175
|
+
def open(self, **body: Any) -> "T.Task":
|
|
176
|
+
"""``budget``, and whose it is: ``reference`` or ``buyer_email`` for a credits account, or ``subscription_id``."""
|
|
177
|
+
return self._c._post("/tasks", _keyed(body), repeatable=True)
|
|
178
|
+
|
|
179
|
+
def close(self, id: str) -> "T.Task":
|
|
180
|
+
return self._c._post(f"/tasks/{_seg(id)}/close", repeatable=True)
|
|
181
|
+
|
|
182
|
+
|
|
183
|
+
class Credits(_Group):
|
|
184
|
+
def get(self, reference: Optional[str] = None, buyer_email: Optional[str] = None) -> "T.CreditBalance":
|
|
185
|
+
return self._c._get("/credits", {"reference": reference, "buyer_email": buyer_email})
|
|
186
|
+
|
|
187
|
+
def use(self, **body: Any) -> "T.CreditSpend":
|
|
188
|
+
"""``amount``, and whose: ``reference`` or ``buyer_email``. Refused (409) when there are not enough."""
|
|
189
|
+
return self._c._post("/credits/use", _keyed(body), repeatable=True)
|
|
190
|
+
|
|
191
|
+
def grant(self, **body: Any) -> "T.CreditGrant":
|
|
192
|
+
return self._c._post("/credits/grant", body)
|
|
193
|
+
|
|
194
|
+
def set_alert(self, at: Optional[int]) -> "T.CreditAlert":
|
|
195
|
+
"""The balance at which credits.low is sent; None for no alert."""
|
|
196
|
+
return self._c._post("/credits/alert", {"at": at}, repeatable=True)
|
|
197
|
+
|
|
198
|
+
|
|
199
|
+
class DiscountCodes(_Group):
|
|
200
|
+
def list(self) -> Listing:
|
|
201
|
+
return self._c._get("/discount_codes")
|
|
202
|
+
|
|
203
|
+
def create(self, **body: Any) -> "T.DiscountCode":
|
|
204
|
+
return self._c._post("/discount_codes", body)
|
|
205
|
+
|
|
206
|
+
|
|
207
|
+
class Partners(_Group):
|
|
208
|
+
def list(self) -> Listing:
|
|
209
|
+
return self._c._get("/partners")
|
|
210
|
+
|
|
211
|
+
def create(self, **body: Any) -> "T.Partner":
|
|
212
|
+
return self._c._post("/partners", body)
|
|
213
|
+
|
|
214
|
+
def set_split(self, id: str, product_id: str, percent: float) -> "T.Partner":
|
|
215
|
+
return self._c._post(f"/partners/{_seg(id)}/split", {"product_id": product_id, "percent": percent}, repeatable=True)
|
|
216
|
+
|
|
217
|
+
def stop(self, id: str) -> "T.Partner":
|
|
218
|
+
"""It cannot be undone."""
|
|
219
|
+
return self._c._post(f"/partners/{_seg(id)}/stop")
|
|
220
|
+
|
|
221
|
+
def approve(self, id: str) -> "T.Partner":
|
|
222
|
+
return self._c._post(f"/partners/{_seg(id)}/approve")
|
|
223
|
+
|
|
224
|
+
def decline(self, id: str) -> "T.DeletedPartner":
|
|
225
|
+
return self._c._post(f"/partners/{_seg(id)}/decline")
|
|
226
|
+
|
|
227
|
+
|
|
228
|
+
class LicenseKeys(_Group):
|
|
229
|
+
def get(self, key: str) -> "T.LicenseKey":
|
|
230
|
+
return self._c._get(f"/license_keys/{_seg(key)}")
|
|
231
|
+
|
|
232
|
+
def activate(self, key: str, instance: str) -> "T.LicenseKey":
|
|
233
|
+
"""Asking again for the same install changes nothing, so call it each time your software starts."""
|
|
234
|
+
return self._c._post(f"/license_keys/{_seg(key)}/activate", {"instance": instance}, repeatable=True)
|
|
235
|
+
|
|
236
|
+
def deactivate(self, key: str, instance: str) -> "T.LicenseKey":
|
|
237
|
+
return self._c._post(f"/license_keys/{_seg(key)}/deactivate", {"instance": instance}, repeatable=True)
|
|
238
|
+
|
|
239
|
+
|
|
240
|
+
class Disputes(_Group):
|
|
241
|
+
"""The sales your buyers' banks have disputed. Recvd answers the bank; what you add goes with its answer."""
|
|
242
|
+
|
|
243
|
+
def list(self, **params: Any) -> Listing:
|
|
244
|
+
return self._c._get("/disputes", params)
|
|
245
|
+
|
|
246
|
+
def all(self, **params: Any) -> Iterator["T.Dispute"]:
|
|
247
|
+
return self._c._all("/disputes", params)
|
|
248
|
+
|
|
249
|
+
def get(self, dispute_id: str) -> "T.Dispute":
|
|
250
|
+
return self._c._get(f"/disputes/{_seg(dispute_id)}")
|
|
251
|
+
|
|
252
|
+
def note(self, dispute_id: str, note: str) -> "T.Dispute":
|
|
253
|
+
return self._c._post(f"/disputes/{_seg(dispute_id)}/note", {"note": note}, repeatable=True)
|
|
254
|
+
|
|
255
|
+
def proof(self, dispute_id: str, **body: Any) -> "T.Dispute":
|
|
256
|
+
"""Only what is named is changed; ``None`` takes a record away. Send only records you hold."""
|
|
257
|
+
return self._c._post(f"/disputes/{_seg(dispute_id)}/proof", body, repeatable=True)
|
|
258
|
+
|
|
259
|
+
|
|
260
|
+
class Portal(_Group):
|
|
261
|
+
"""The customer portal in your own app. Each change acts as the buyer: it is held to what the buyer may do alone."""
|
|
262
|
+
|
|
263
|
+
def _do(self, id: str, verb: str, body: Optional[Dict[str, Any]] = None, repeatable: bool = False) -> Any:
|
|
264
|
+
return self._c._post(f"/portal/{_seg(id)}/{verb}", body, repeatable=repeatable)
|
|
265
|
+
|
|
266
|
+
def get(self, reference: Optional[str] = None, buyer_email: Optional[str] = None) -> "T.Portal":
|
|
267
|
+
"""Everything one buyer has with you."""
|
|
268
|
+
return self._c._get("/portal", {"reference": reference, "buyer_email": buyer_email})
|
|
269
|
+
|
|
270
|
+
def link(self, subscription_id: str) -> "T.PortalLink":
|
|
271
|
+
"""The buyer's own link. It is the buyer's key: give it only to that buyer, and keep it out of logs."""
|
|
272
|
+
return self._do(subscription_id, "link", repeatable=True)
|
|
273
|
+
|
|
274
|
+
def cancel(self, subscription_id: str, reason: Optional[str] = None, note: Optional[str] = None) -> "T.PortalSubscription":
|
|
275
|
+
"""It cannot be undone."""
|
|
276
|
+
return self._do(subscription_id, "cancel", _clean({"reason": reason, "note": note}))
|
|
277
|
+
|
|
278
|
+
def reason(self, subscription_id: str, reason: str, note: Optional[str] = None) -> "T.PortalSubscription":
|
|
279
|
+
return self._do(subscription_id, "reason", _clean({"reason": reason, "note": note}), repeatable=True)
|
|
280
|
+
|
|
281
|
+
def change_plan(self, subscription_id: str, product_id: str) -> "T.PortalSubscription":
|
|
282
|
+
return self._do(subscription_id, "change", {"product_id": product_id})
|
|
283
|
+
|
|
284
|
+
def change_seats(self, subscription_id: str, seats: int) -> "T.PortalSubscription":
|
|
285
|
+
return self._do(subscription_id, "seats", {"seats": seats})
|
|
286
|
+
|
|
287
|
+
def pause(self, subscription_id: str, months: int) -> "T.PortalSubscription":
|
|
288
|
+
return self._do(subscription_id, "pause", {"months": months})
|
|
289
|
+
|
|
290
|
+
def resume(self, subscription_id: str) -> "T.PortalSubscription":
|
|
291
|
+
return self._do(subscription_id, "resume")
|
|
292
|
+
|
|
293
|
+
def lower_price(self, subscription_id: str, price_cents: int, renewals: int, then_cents: int) -> "T.PortalSubscription":
|
|
294
|
+
"""The terms as the buyer was shown them; refused (409) if they are not the offer now."""
|
|
295
|
+
return self._do(subscription_id, "lower_price", {"price_cents": price_cents, "renewals": renewals, "then_cents": then_cents})
|
|
296
|
+
|
|
297
|
+
def set_offers(self, on: bool, percent: Optional[int] = None, renewals: Optional[int] = None) -> "T.CancelOffers":
|
|
298
|
+
return self._c._post("/portal/offers", _clean({"on": on, "percent": percent, "renewals": renewals}), repeatable=True)
|
|
299
|
+
|
|
300
|
+
|
|
301
|
+
class Buyers(_Group):
|
|
302
|
+
def list(self, buyer_email: Optional[str] = None) -> Listing:
|
|
303
|
+
return self._c._get("/buyers", {"buyer_email": buyer_email})
|
|
304
|
+
|
|
305
|
+
|
|
306
|
+
class Stats(_Group):
|
|
307
|
+
def get(self) -> "T.Stats":
|
|
308
|
+
return self._c._get("/stats")
|
|
309
|
+
|
|
310
|
+
|
|
311
|
+
class Events(_Group):
|
|
312
|
+
def list(self, after: Optional[str] = None, limit: Optional[int] = None) -> Listing:
|
|
313
|
+
"""The events of the last thirty days, oldest first: the latest ones, or with ``after`` the ones made after that event."""
|
|
314
|
+
return self._c._get("/events", {"after": after, "limit": limit})
|
|
315
|
+
|
|
316
|
+
|
|
317
|
+
class CheckoutLinks(_Group):
|
|
318
|
+
def create(self, **body: Any) -> "T.CheckoutLink":
|
|
319
|
+
return self._c._post("/checkout_links", body, repeatable=True)
|
|
320
|
+
|
|
321
|
+
|
|
322
|
+
def _seg(value: str) -> str:
|
|
323
|
+
return urllib.parse.quote(str(value), safe="")
|
|
324
|
+
|
|
325
|
+
|
|
326
|
+
class Recvd:
|
|
327
|
+
def __init__(self, api_key: str, *, base_url: str = "https://recvd.co/api/v1", max_retries: int = 2, timeout: float = 30.0, retry_delay: float = 0.3, transport: Optional[Transport] = None) -> None:
|
|
328
|
+
"""``max_retries``: how many times a request that is safe to repeat is tried again after a network failure, a 429 or a 5xx."""
|
|
329
|
+
if not api_key:
|
|
330
|
+
raise RecvdError(0, 'Give your Recvd API key: Recvd(os.environ["RECVD_API_KEY"])')
|
|
331
|
+
self._key, self._base, self._retries, self._timeout, self._delay = api_key, base_url.rstrip("/"), max_retries, timeout, retry_delay
|
|
332
|
+
self._transport: Transport = transport or _urllib
|
|
333
|
+
self.products, self.sales, self.subscriptions = Products(self), Sales(self), Subscriptions(self)
|
|
334
|
+
self.usage_charges, self.usage_events, self.tasks = UsageCharges(self), UsageEvents(self), Tasks(self)
|
|
335
|
+
self.credits, self.discount_codes, self.partners = Credits(self), DiscountCodes(self), Partners(self)
|
|
336
|
+
self.license_keys, self.buyers, self.stats = LicenseKeys(self), Buyers(self), Stats(self)
|
|
337
|
+
self.events, self.checkout_links, self.portal, self.disputes = Events(self), CheckoutLinks(self), Portal(self), Disputes(self)
|
|
338
|
+
|
|
339
|
+
def request(self, method: str, path: str, *, query: Optional[Dict[str, Any]] = None, body: Optional[Any] = None, repeatable: bool = False) -> Any:
|
|
340
|
+
"""One request.
|
|
341
|
+
|
|
342
|
+
A GET, and a write that carries an idempotency key, is tried again after a network failure, a 429 or a 5xx;
|
|
343
|
+
any other write is sent once, because sending it twice could do it twice.
|
|
344
|
+
"""
|
|
345
|
+
asked = urllib.parse.urlencode(_clean(query or {}))
|
|
346
|
+
url = f"{self._base}{path}{'?' + asked if asked else ''}"
|
|
347
|
+
headers = {"Authorization": f"Bearer {self._key}", "Accept": "application/json", "User-Agent": f"recvd-python/{VERSION}"}
|
|
348
|
+
data = None
|
|
349
|
+
if method == "POST":
|
|
350
|
+
headers["Content-Type"] = "application/json"
|
|
351
|
+
data = json.dumps(body if body is not None else {}).encode("utf-8")
|
|
352
|
+
tries = 1 + max(0, int(self._retries)) if method == "GET" or repeatable else 1
|
|
353
|
+
attempt = 0
|
|
354
|
+
while True:
|
|
355
|
+
attempt += 1
|
|
356
|
+
try:
|
|
357
|
+
status, raw = self._transport(method, url, headers, data, self._timeout)
|
|
358
|
+
try:
|
|
359
|
+
answer = json.loads(raw.decode("utf-8"))
|
|
360
|
+
except ValueError as error:
|
|
361
|
+
# Every answer is JSON. A 2xx whose body did not arrive whole is a failed request, not an empty answer.
|
|
362
|
+
if 200 <= status < 300:
|
|
363
|
+
raise http.client.IncompleteRead(raw) from error
|
|
364
|
+
answer = None
|
|
365
|
+
if 200 <= status < 300:
|
|
366
|
+
return answer
|
|
367
|
+
said = answer.get("error") if isinstance(answer, dict) and isinstance(answer.get("error"), str) else f"Recvd answered {status}"
|
|
368
|
+
failure: RecvdError = RecvdError(status, said, answer)
|
|
369
|
+
except (OSError, http.client.HTTPException) as error: # URLError, a timeout and a refused connection are all OSError
|
|
370
|
+
failure = RecvdConnectionError(error)
|
|
371
|
+
# What Recvd refused in words (a 4xx) is final; no answer, a 429 or a 5xx may be asked again.
|
|
372
|
+
if attempt >= tries or not (failure.status == 0 or failure.status == 429 or failure.status >= 500):
|
|
373
|
+
raise failure
|
|
374
|
+
time.sleep(self._delay * 3 ** (attempt - 1))
|
|
375
|
+
|
|
376
|
+
def _get(self, path: str, query: Optional[Dict[str, Any]] = None) -> Any:
|
|
377
|
+
return self.request("GET", path, query=query)
|
|
378
|
+
|
|
379
|
+
def _post(self, path: str, body: Optional[Any] = None, repeatable: bool = False) -> Any:
|
|
380
|
+
return self.request("POST", path, body=body, repeatable=repeatable)
|
|
381
|
+
|
|
382
|
+
def _all(self, path: str, params: Dict[str, Any]) -> Iterator[Any]:
|
|
383
|
+
"""Every item of a list, page after page."""
|
|
384
|
+
after = params.get("starting_after")
|
|
385
|
+
while True:
|
|
386
|
+
page = self._get(path, {**params, "starting_after": after})
|
|
387
|
+
yield from page["data"]
|
|
388
|
+
if not page["has_more"] or not page["data"]:
|
|
389
|
+
return
|
|
390
|
+
after = page["data"][-1]["id"]
|
|
391
|
+
|
|
392
|
+
def meter(self, **options: Any) -> Metered:
|
|
393
|
+
"""Wraps calls to an OpenAI or Anthropic client so the tokens each answer reports are sent to Recvd as usage events.
|
|
394
|
+
|
|
395
|
+
Only the counts and the answer's id are sent, never a prompt or an answer. See ``recvd.metering.Metered``.
|
|
396
|
+
"""
|
|
397
|
+
return Metered(self, **options)
|
recvd/errors.py
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from typing import Any, Optional
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
class RecvdError(Exception):
|
|
7
|
+
"""Recvd refused a request, or could not be reached.
|
|
8
|
+
|
|
9
|
+
``status`` is the HTTP status (0 when there was no answer), ``message`` is what Recvd said,
|
|
10
|
+
and ``body`` is the answer's body when there was one.
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
def __init__(self, status: int, message: str, body: Optional[Any] = None) -> None:
|
|
14
|
+
super().__init__(message)
|
|
15
|
+
self.status = status
|
|
16
|
+
self.message = message
|
|
17
|
+
self.body = body
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
class RecvdConnectionError(RecvdError):
|
|
21
|
+
"""No answer came: the network failed, or the request took too long."""
|
|
22
|
+
|
|
23
|
+
def __init__(self, cause: BaseException) -> None:
|
|
24
|
+
super().__init__(0, f"Recvd could not be reached: {cause}")
|
|
25
|
+
self.__cause__ = cause
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
class RecvdSignatureError(Exception):
|
|
29
|
+
"""A webhook did not carry a signature made with your signing secret, or is too old. Do not believe the event."""
|