sendurl 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.
sendurl/_base.py ADDED
@@ -0,0 +1,343 @@
1
+ """The transport shared by both clients: configuration, request building,
2
+ retries and error mapping. The sync and async clients differ only in how
3
+ they send a request and sleep; everything else lives here once."""
4
+
5
+ from __future__ import annotations
6
+
7
+ import asyncio
8
+ import os
9
+ import random
10
+ import time
11
+ from dataclasses import dataclass, field
12
+ from typing import (
13
+ Any,
14
+ AsyncIterator,
15
+ Callable,
16
+ Dict,
17
+ Iterator,
18
+ Mapping,
19
+ Optional,
20
+ Union,
21
+ )
22
+
23
+ import httpx
24
+
25
+ from ._errors import (
26
+ APIConnectionError,
27
+ APITimeoutError,
28
+ SendURLError,
29
+ error_from_response,
30
+ parse_retry_after,
31
+ )
32
+ from ._version import __version__
33
+
34
+ DEFAULT_BASE_URL = "https://api.sendurl.to/api/v1"
35
+ DEFAULT_TIMEOUT = 30.0
36
+ DEFAULT_MAX_RETRIES = 2
37
+ USER_AGENT = f"sendurl-python/{__version__}"
38
+
39
+ # Retries: only for GET (the API has no idempotency key, so a retried POST
40
+ # could create a link twice), on these statuses or a connection failure.
41
+ RETRY_STATUSES = frozenset({429, 502, 503, 504})
42
+ INITIAL_BACKOFF = 0.5
43
+ MAX_BACKOFF = 8.0
44
+ MAX_RETRY_AFTER = 60.0
45
+
46
+
47
+ @dataclass(frozen=True)
48
+ class Req:
49
+ """One API call, before it is sent: method, path under the base URL, query, JSON body."""
50
+
51
+ method: str
52
+ path: str
53
+ params: Mapping[str, str] = field(default_factory=dict)
54
+ json: Optional[Mapping[str, Any]] = None
55
+
56
+
57
+ def _sleep(seconds: float) -> None:
58
+ time.sleep(seconds)
59
+
60
+
61
+ async def _asleep(seconds: float) -> None:
62
+ await asyncio.sleep(seconds)
63
+
64
+
65
+ LOOPBACK_HOSTS = frozenset({"localhost", "127.0.0.1", "::1"})
66
+
67
+
68
+ def _checked_base_url(url: str) -> str:
69
+ """The base URL, refused unless it is https (or http on a loopback host),
70
+ so the API key is never sent in clear text over a network."""
71
+ try:
72
+ parsed = httpx.URL(url)
73
+ except Exception:
74
+ raise SendURLError("base_url is not a valid URL.") from None
75
+ scheme = parsed.scheme.lower()
76
+ host = parsed.host.lower().strip("[]")
77
+ if not host:
78
+ raise SendURLError("base_url must be an absolute https:// URL.")
79
+ if scheme == "https":
80
+ return url
81
+ if scheme == "http" and host in LOOPBACK_HOSTS:
82
+ return url
83
+ raise SendURLError(
84
+ "base_url must use https:// (http:// is allowed only for localhost, 127.0.0.1 and ::1), "
85
+ "so the API key is never sent in clear text."
86
+ )
87
+
88
+
89
+ def _query_value(value: Any) -> str:
90
+ if isinstance(value, bool):
91
+ return "true" if value else "false"
92
+ return str(value)
93
+
94
+
95
+ class BaseClient:
96
+ """Configuration and the parts of a request that don't depend on sync or async."""
97
+
98
+ base_url: str
99
+ timeout: Union[float, httpx.Timeout]
100
+ max_retries: int
101
+
102
+ def __init__(
103
+ self,
104
+ *,
105
+ api_key: Optional[str],
106
+ base_url: Optional[str],
107
+ timeout: Union[float, httpx.Timeout, None],
108
+ max_retries: int,
109
+ ) -> None:
110
+ key = api_key if api_key is not None else os.environ.get("SENDURL_API_KEY")
111
+ if not isinstance(key, str) or not key.strip():
112
+ raise SendURLError(
113
+ "No API key: pass api_key=... or set the SENDURL_API_KEY environment variable."
114
+ )
115
+ # Name-mangled and never part of repr() or any error message.
116
+ self.__api_key = key.strip()
117
+ url = base_url or os.environ.get("SENDURL_BASE_URL") or DEFAULT_BASE_URL
118
+ self.base_url = _checked_base_url(url).rstrip("/")
119
+ self.timeout = DEFAULT_TIMEOUT if timeout is None else timeout
120
+ if not isinstance(max_retries, int) or max_retries < 0:
121
+ raise ValueError("max_retries must be a non-negative integer")
122
+ self.max_retries = max_retries
123
+
124
+ def __repr__(self) -> str:
125
+ return f"{type(self).__name__}(base_url={self.base_url!r})"
126
+
127
+ # --- building -------------------------------------------------------------
128
+
129
+ def _headers(self, has_body: bool) -> Dict[str, str]:
130
+ headers = {
131
+ "Authorization": f"Bearer {self.__api_key}",
132
+ "Accept": "application/json",
133
+ "User-Agent": USER_AGENT,
134
+ }
135
+ if has_body:
136
+ headers["Content-Type"] = "application/json"
137
+ return headers
138
+
139
+ def _build(self, http: Union[httpx.Client, httpx.AsyncClient], req: Req) -> httpx.Request:
140
+ params = {k: _query_value(v) for k, v in req.params.items()}
141
+ return http.build_request(
142
+ req.method,
143
+ f"{self.base_url}{req.path}",
144
+ params=params or None,
145
+ json=dict(req.json) if req.json is not None else None,
146
+ headers=self._headers(req.json is not None),
147
+ timeout=self.timeout,
148
+ )
149
+
150
+ # --- retries --------------------------------------------------------------
151
+
152
+ def _can_retry(self, req: Req, attempt: int) -> bool:
153
+ return req.method == "GET" and attempt < self.max_retries
154
+
155
+ def _retry_delay(self, attempt: int, response: Optional[httpx.Response]) -> float:
156
+ if response is not None:
157
+ retry_after = parse_retry_after(response.headers.get("retry-after"))
158
+ if retry_after is not None:
159
+ return min(retry_after, MAX_RETRY_AFTER)
160
+ backoff: float = min(INITIAL_BACKOFF * (2**attempt), MAX_BACKOFF)
161
+ # Full jitter on the upper quarter, so concurrent clients spread out.
162
+ return backoff * (0.75 + random.random() * 0.25)
163
+
164
+ # --- answers --------------------------------------------------------------
165
+
166
+ @staticmethod
167
+ def _error(response: httpx.Response) -> SendURLError:
168
+ return error_from_response(
169
+ response.status_code, response.headers, response.content, response.reason_phrase
170
+ )
171
+
172
+ @staticmethod
173
+ def _redirect_error(response: httpx.Response) -> SendURLError:
174
+ return SendURLError(
175
+ f"The API answered with a redirect ({response.status_code}), which is never followed "
176
+ "(it could send the API key elsewhere). Check base_url: it should be "
177
+ f"{DEFAULT_BASE_URL} or your own platform's /api/v1.",
178
+ status_code=response.status_code,
179
+ )
180
+
181
+ @staticmethod
182
+ def _parse(response: httpx.Response) -> Any:
183
+ if not response.content:
184
+ return None
185
+ try:
186
+ return response.json()
187
+ except ValueError:
188
+ raise SendURLError(
189
+ "The API answered with a body that isn't JSON.",
190
+ status_code=response.status_code,
191
+ ) from None
192
+
193
+ @staticmethod
194
+ def _transport_error(exc: httpx.TransportError) -> SendURLError:
195
+ if isinstance(exc, httpx.TimeoutException):
196
+ return APITimeoutError(f"Request timed out ({type(exc).__name__}).")
197
+ return APIConnectionError(f"Connection error ({type(exc).__name__}): {exc}")
198
+
199
+
200
+ class SyncTransport(BaseClient):
201
+ """Sends requests with an ``httpx.Client``."""
202
+
203
+ _http: httpx.Client
204
+
205
+ def __init__(
206
+ self,
207
+ *,
208
+ api_key: Optional[str],
209
+ base_url: Optional[str],
210
+ timeout: Union[float, httpx.Timeout, None],
211
+ max_retries: int,
212
+ http_client: Optional[httpx.Client],
213
+ ) -> None:
214
+ super().__init__(api_key=api_key, base_url=base_url, timeout=timeout, max_retries=max_retries)
215
+ self._owns_http = http_client is None
216
+ self._http = http_client if http_client is not None else httpx.Client()
217
+
218
+ def close(self) -> None:
219
+ """Close the underlying HTTP client (not one you passed in as ``http_client``)."""
220
+ if self._owns_http:
221
+ self._http.close()
222
+
223
+ def _send(self, req: Req, *, stream: bool = False) -> httpx.Response:
224
+ attempt = 0
225
+ while True:
226
+ request = self._build(self._http, req)
227
+ try:
228
+ response = self._http.send(request, stream=stream, follow_redirects=False)
229
+ except httpx.TransportError as exc:
230
+ if self._can_retry(req, attempt):
231
+ _sleep(self._retry_delay(attempt, None))
232
+ attempt += 1
233
+ continue
234
+ raise self._transport_error(exc) from exc
235
+ if response.status_code < 300:
236
+ return response
237
+ if response.status_code < 400:
238
+ response.close()
239
+ raise self._redirect_error(response)
240
+ if response.status_code in RETRY_STATUSES and self._can_retry(req, attempt):
241
+ delay = self._retry_delay(attempt, response)
242
+ response.close()
243
+ _sleep(delay)
244
+ attempt += 1
245
+ continue
246
+ try:
247
+ response.read()
248
+ finally:
249
+ response.close()
250
+ raise self._error(response)
251
+
252
+ def _request(self, req: Req) -> Any:
253
+ return self._parse(self._send(req))
254
+
255
+ def _paginate(self, build: Callable[[Optional[str]], Req], items_key: str) -> Iterator[Any]:
256
+ cursor: Optional[str] = None
257
+ while True:
258
+ page = self._request(build(cursor))
259
+ if not isinstance(page, dict):
260
+ return
261
+ yield from page.get(items_key) or []
262
+ pagination = page.get("pagination") or {}
263
+ cursor = pagination.get("nextCursor")
264
+ if not pagination.get("hasMore") or not cursor:
265
+ return
266
+
267
+
268
+ class AsyncTransport(BaseClient):
269
+ """Sends requests with an ``httpx.AsyncClient``."""
270
+
271
+ _http: httpx.AsyncClient
272
+
273
+ def __init__(
274
+ self,
275
+ *,
276
+ api_key: Optional[str],
277
+ base_url: Optional[str],
278
+ timeout: Union[float, httpx.Timeout, None],
279
+ max_retries: int,
280
+ http_client: Optional[httpx.AsyncClient],
281
+ ) -> None:
282
+ super().__init__(api_key=api_key, base_url=base_url, timeout=timeout, max_retries=max_retries)
283
+ self._owns_http = http_client is None
284
+ self._http = http_client if http_client is not None else httpx.AsyncClient()
285
+
286
+ async def aclose(self) -> None:
287
+ """Close the underlying HTTP client (not one you passed in as ``http_client``)."""
288
+ if self._owns_http:
289
+ await self._http.aclose()
290
+
291
+ async def _send(self, req: Req, *, stream: bool = False) -> httpx.Response:
292
+ attempt = 0
293
+ while True:
294
+ request = self._build(self._http, req)
295
+ try:
296
+ response = await self._http.send(request, stream=stream, follow_redirects=False)
297
+ except httpx.TransportError as exc:
298
+ if self._can_retry(req, attempt):
299
+ await _asleep(self._retry_delay(attempt, None))
300
+ attempt += 1
301
+ continue
302
+ raise self._transport_error(exc) from exc
303
+ if response.status_code < 300:
304
+ return response
305
+ if response.status_code < 400:
306
+ await response.aclose()
307
+ raise self._redirect_error(response)
308
+ if response.status_code in RETRY_STATUSES and self._can_retry(req, attempt):
309
+ delay = self._retry_delay(attempt, response)
310
+ await response.aclose()
311
+ await _asleep(delay)
312
+ attempt += 1
313
+ continue
314
+ try:
315
+ await response.aread()
316
+ finally:
317
+ await response.aclose()
318
+ raise self._error(response)
319
+
320
+ async def _request(self, req: Req) -> Any:
321
+ return self._parse(await self._send(req))
322
+
323
+ async def _paginate(self, build: Callable[[Optional[str]], Req], items_key: str) -> AsyncIterator[Any]:
324
+ cursor: Optional[str] = None
325
+ while True:
326
+ page = await self._request(build(cursor))
327
+ if not isinstance(page, dict):
328
+ return
329
+ for item in page.get(items_key) or []:
330
+ yield item
331
+ pagination = page.get("pagination") or {}
332
+ cursor = pagination.get("nextCursor")
333
+ if not pagination.get("hasMore") or not cursor:
334
+ return
335
+
336
+
337
+ __all__ = [
338
+ "DEFAULT_BASE_URL",
339
+ "AsyncTransport",
340
+ "BaseClient",
341
+ "Req",
342
+ "SyncTransport",
343
+ ]
sendurl/_endpoints.py ADDED
@@ -0,0 +1,315 @@
1
+ """Every API call as a pure function from Python arguments to a :class:`Req`.
2
+
3
+ Both clients' resources call these, so the mapping from snake_case arguments
4
+ to the API's camelCase query and body (and every conversion) is written once.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import datetime as _dt
10
+ from typing import Any, Dict, Mapping, Optional, Sequence, Union
11
+
12
+ from ._base import Req
13
+ from ._utils import (
14
+ NotGiven,
15
+ bool_param,
16
+ compact,
17
+ csv_param,
18
+ given,
19
+ iso_date,
20
+ iso_datetime,
21
+ path_segment,
22
+ )
23
+
24
+ DateLike = Union[_dt.date, str]
25
+ DateTimeLike = Union[_dt.datetime, str]
26
+ StrOrList = Union[str, Sequence[str]]
27
+
28
+
29
+ def _links(link_id: str) -> str:
30
+ return f"/links/{path_segment(link_id, 'link_id')}"
31
+
32
+
33
+ def _page_params(limit: Optional[int], cursor: Optional[str]) -> Dict[str, Any]:
34
+ return compact({"limit": limit, "cursor": cursor})
35
+
36
+
37
+ def _tag_ids(value: Optional[Sequence[str]]) -> Optional[list[str]]:
38
+ if value is None:
39
+ return None
40
+ if isinstance(value, str):
41
+ raise TypeError("tag_ids must be a list of tag ids, not a string")
42
+ return list(value)
43
+
44
+
45
+ def _expires(value: Union[DateTimeLike, NotGiven, None]) -> Union[str, NotGiven, None]:
46
+ if value is None or isinstance(value, NotGiven):
47
+ return value
48
+ return iso_datetime(value, "expires_at")
49
+
50
+
51
+ def _obj(value: Union[Mapping[str, Any], NotGiven, None]) -> Union[Dict[str, Any], NotGiven, None]:
52
+ if value is None or isinstance(value, NotGiven):
53
+ return value
54
+ return dict(value)
55
+
56
+
57
+ def _qr_style(value: Union[Mapping[str, Any], NotGiven, None]) -> Union[Dict[str, Any], NotGiven, None]:
58
+ """A QR style with its version: the API takes exactly fg, bg, dots, corners and v (1)."""
59
+ if value is None or isinstance(value, NotGiven):
60
+ return value
61
+ style = dict(value)
62
+ style.setdefault("v", 1)
63
+ return style
64
+
65
+
66
+ # --- account -----------------------------------------------------------------
67
+
68
+
69
+ def account_get() -> Req:
70
+ return Req("GET", "/me")
71
+
72
+
73
+ # --- links -------------------------------------------------------------------
74
+
75
+
76
+ def links_create(
77
+ *,
78
+ destination_url: str,
79
+ slug: Optional[str],
80
+ title: Optional[str],
81
+ folder_id: Optional[str],
82
+ domain_id: Optional[str],
83
+ expires_at: Optional[DateTimeLike],
84
+ password: Optional[str],
85
+ ios_url: Optional[str],
86
+ android_url: Optional[str],
87
+ tag_ids: Optional[Sequence[str]],
88
+ qr_style: Optional[Mapping[str, Any]],
89
+ preview: Optional[Mapping[str, Any]],
90
+ ab_test: Optional[Mapping[str, Any]],
91
+ ) -> Req:
92
+ body = compact(
93
+ {
94
+ "destinationUrl": destination_url,
95
+ "slug": slug,
96
+ "title": title,
97
+ "folderId": folder_id,
98
+ "domainId": domain_id,
99
+ "expiresAt": _expires(expires_at),
100
+ "password": password,
101
+ "iosUrl": ios_url,
102
+ "androidUrl": android_url,
103
+ "tagIds": _tag_ids(tag_ids),
104
+ "qrStyle": _qr_style(qr_style),
105
+ "preview": _obj(preview),
106
+ "abTest": _obj(ab_test),
107
+ }
108
+ )
109
+ return Req("POST", "/links", json=body)
110
+
111
+
112
+ def links_list(
113
+ *,
114
+ status: Optional[StrOrList],
115
+ q: Optional[str],
116
+ sort: Optional[str],
117
+ folder_id: Optional[str],
118
+ tag_ids: Optional[Sequence[str]],
119
+ limit: Optional[int],
120
+ cursor: Optional[str],
121
+ ) -> Req:
122
+ tags = _tag_ids(tag_ids)
123
+ params = compact(
124
+ {
125
+ "status": csv_param(status) if status is not None else None,
126
+ "q": q,
127
+ "sort": sort,
128
+ "folderId": folder_id,
129
+ "tagIds": ",".join(tags) if tags else None,
130
+ }
131
+ )
132
+ params.update(_page_params(limit, cursor))
133
+ return Req("GET", "/links", params=params)
134
+
135
+
136
+ def links_get(link_id: str) -> Req:
137
+ return Req("GET", _links(link_id))
138
+
139
+
140
+ def links_update(
141
+ link_id: str,
142
+ *,
143
+ destination_url: Union[str, NotGiven],
144
+ title: Union[str, NotGiven, None],
145
+ active: Union[bool, NotGiven],
146
+ folder_id: Union[str, NotGiven],
147
+ expires_at: Union[DateTimeLike, NotGiven, None],
148
+ password: Union[str, NotGiven, None],
149
+ ios_url: Union[str, NotGiven, None],
150
+ android_url: Union[str, NotGiven, None],
151
+ tag_ids: Union[Sequence[str], NotGiven, None],
152
+ qr_style: Union[Mapping[str, Any], NotGiven, None],
153
+ preview: Union[Mapping[str, Any], NotGiven, None],
154
+ ab_test: Union[Mapping[str, Any], NotGiven, None],
155
+ ) -> Req:
156
+ body = given(
157
+ {
158
+ "destinationUrl": destination_url,
159
+ "title": title,
160
+ "active": active,
161
+ "folderId": folder_id,
162
+ "expiresAt": _expires(expires_at),
163
+ "password": password,
164
+ "iosUrl": ios_url,
165
+ "androidUrl": android_url,
166
+ "tagIds": tag_ids if isinstance(tag_ids, NotGiven) else _tag_ids(tag_ids),
167
+ "qrStyle": _qr_style(qr_style),
168
+ "preview": _obj(preview),
169
+ "abTest": _obj(ab_test),
170
+ }
171
+ )
172
+ return Req("PATCH", _links(link_id), json=body)
173
+
174
+
175
+ def links_delete(link_id: str) -> Req:
176
+ return Req("DELETE", _links(link_id))
177
+
178
+
179
+ def links_pick_winner(link_id: str, *, variant_id: str) -> Req:
180
+ return Req("POST", f"{_links(link_id)}/ab-test/winner", json={"variantId": variant_id})
181
+
182
+
183
+ def links_export(
184
+ *,
185
+ status: Optional[StrOrList],
186
+ q: Optional[str],
187
+ folder_id: Optional[str],
188
+ tag_ids: Optional[Sequence[str]],
189
+ ) -> Req:
190
+ tags = _tag_ids(tag_ids)
191
+ params = compact(
192
+ {
193
+ "status": csv_param(status) if status is not None else None,
194
+ "q": q,
195
+ "folderId": folder_id,
196
+ "tagIds": ",".join(tags) if tags else None,
197
+ }
198
+ )
199
+ return Req("GET", "/links/export.csv", params=params)
200
+
201
+
202
+ def links_stats(link_id: str) -> Req:
203
+ return Req("GET", f"{_links(link_id)}/stats")
204
+
205
+
206
+ def link_clicks_list(link_id: str, *, limit: Optional[int], cursor: Optional[str]) -> Req:
207
+ return Req("GET", f"{_links(link_id)}/clicks", params=_page_params(limit, cursor))
208
+
209
+
210
+ def link_clicks_get(link_id: str, click_id: str) -> Req:
211
+ return Req("GET", f"{_links(link_id)}/clicks/{path_segment(click_id, 'click_id')}")
212
+
213
+
214
+ # --- analytics ---------------------------------------------------------------
215
+
216
+
217
+ def _range(
218
+ from_: DateLike,
219
+ to: DateLike,
220
+ tz: Optional[str],
221
+ folder_id: Optional[str],
222
+ link_id: Optional[str],
223
+ ) -> Dict[str, Any]:
224
+ return compact(
225
+ {
226
+ "from": iso_date(from_, "from_"),
227
+ "to": iso_date(to, "to"),
228
+ "tz": tz,
229
+ "folderId": folder_id,
230
+ "linkId": link_id,
231
+ }
232
+ )
233
+
234
+
235
+ def analytics_overview(
236
+ *,
237
+ from_: DateLike,
238
+ to: DateLike,
239
+ tz: Optional[str],
240
+ folder_id: Optional[str],
241
+ link_id: Optional[str],
242
+ compare: Optional[bool],
243
+ ) -> Req:
244
+ params = _range(from_, to, tz, folder_id, link_id)
245
+ if compare is not None:
246
+ params["compare"] = bool_param(compare)
247
+ return Req("GET", "/analytics/overview", params=params)
248
+
249
+
250
+ def analytics_breakdown(
251
+ *,
252
+ from_: DateLike,
253
+ to: DateLike,
254
+ dimension: str,
255
+ tz: Optional[str],
256
+ folder_id: Optional[str],
257
+ link_id: Optional[str],
258
+ order: Optional[str],
259
+ limit: Optional[int],
260
+ by: Optional[str],
261
+ category: Optional[str],
262
+ count_only: Optional[bool],
263
+ ) -> Req:
264
+ params = _range(from_, to, tz, folder_id, link_id)
265
+ params.update(
266
+ compact(
267
+ {
268
+ "dimension": dimension,
269
+ "order": order,
270
+ "limit": limit,
271
+ "by": by,
272
+ "category": category,
273
+ "countOnly": bool_param(count_only) if count_only is not None else None,
274
+ }
275
+ )
276
+ )
277
+ return Req("GET", "/analytics/breakdown", params=params)
278
+
279
+
280
+ def analytics_clicks(
281
+ *,
282
+ from_: DateLike,
283
+ to: DateLike,
284
+ tz: Optional[str],
285
+ folder_id: Optional[str],
286
+ link_id: Optional[str],
287
+ limit: Optional[int],
288
+ cursor: Optional[str],
289
+ ) -> Req:
290
+ params = _range(from_, to, tz, folder_id, link_id)
291
+ params.update(_page_params(limit, cursor))
292
+ return Req("GET", "/analytics/clicks", params=params)
293
+
294
+
295
+ # --- folders, tags, domains --------------------------------------------------
296
+
297
+
298
+ def folders_list(*, limit: Optional[int], cursor: Optional[str]) -> Req:
299
+ return Req("GET", "/folders", params=_page_params(limit, cursor))
300
+
301
+
302
+ def folders_create(*, name: str) -> Req:
303
+ return Req("POST", "/folders", json={"name": name})
304
+
305
+
306
+ def tags_list(*, limit: Optional[int], cursor: Optional[str]) -> Req:
307
+ return Req("GET", "/tags", params=_page_params(limit, cursor))
308
+
309
+
310
+ def domains_list(*, limit: Optional[int], cursor: Optional[str]) -> Req:
311
+ return Req("GET", "/domains", params=_page_params(limit, cursor))
312
+
313
+
314
+ def domains_get(domain_id: str) -> Req:
315
+ return Req("GET", f"/domains/{path_segment(domain_id, 'domain_id')}")