eddieland-canopy-http 0.14.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.
@@ -0,0 +1,393 @@
1
+ """canopy's HTTP client for the programs it ships: the GitHub programs, the Jira connector, and the Slack sink (D130).
2
+
3
+ Each holds a credential the harness never does (TRUST_MODEL T2) and talks to one service. This is the one way they
4
+ talk to it: a client bound to one origin that follows no redirect, so a credential goes nowhere else; the system's
5
+ certificates, so an Enterprise host's own CA works; and one account of what went wrong, which says whether the request
6
+ may have been carried out, so a caller knows whether sending it again could do it twice.
7
+
8
+ A request is sent again, after each of `Retry.pauses`, when that cannot do it twice: when it never left, or when the
9
+ service refused it and said how long to wait (a 429, or a refusal naming `Retry-After`) for no longer than
10
+ `Retry.longest_wait`. A request its caller marks `again`, as a read is, is also sent again when it may have been
11
+ carried out: a server error, or a reply that broke off or is not JSON when JSON was asked for, or that reports a failure
12
+ of the service's own though its status is a success. A request that timed out is never sent again: it has spent its
13
+ timeout once already, which a connector's run cannot spend many times over. Each pause is moved at random by up to
14
+ `Retry.jitter` of it, so that programs that failed together do not all try again at once.
15
+
16
+ It honors the environment's proxy (`HTTPS_PROXY`) and certificates (`SSL_CERT_FILE`), as urllib did: an operator
17
+ behind a proxy reaches the service through it, which sees the request as it would any other of theirs.
18
+
19
+ httpx2 for the transport, and nothing from canopy.
20
+ """
21
+
22
+ from __future__ import annotations
23
+
24
+ import email.utils
25
+ import json
26
+ import random
27
+ import ssl
28
+ import time
29
+ import urllib.parse
30
+ from collections.abc import Callable, Mapping, Sequence
31
+ from dataclasses import dataclass
32
+ from datetime import UTC, datetime
33
+ from typing import Final
34
+
35
+ import httpx2
36
+
37
+ #: How long a request waits on its reply, between reads of it.
38
+ TIMEOUT_SECONDS: Final = 30.0
39
+ #: How long it waits to connect: a host that has not answered by then is not going to.
40
+ CONNECT_SECONDS: Final = 10.0
41
+ #: How much of a reply an error quotes.
42
+ MAX_QUOTE: Final = 500
43
+ #: The refusals that ask for a wait, when they name one: a rate limit, and GitHub's secondary rate limit, a 403.
44
+ _WAIT_STATUSES: Final = frozenset({403, 429})
45
+ _TOO_MANY: Final = 429
46
+ #: How far down the errors one was raised from `_untrusted` looks: httpx2's wraps its transport's, which wraps TLS's.
47
+ _MAX_CHAIN: Final = 10
48
+
49
+
50
+ class HttpError(Exception):
51
+ """A request that failed.
52
+
53
+ `certain` is whether it is known not to have been carried out: it never left, or the service refused it. A request
54
+ that broke off, timed out, or got a server error may have been carried out.
55
+ """
56
+
57
+ def __init__(
58
+ self,
59
+ message: str,
60
+ *,
61
+ certain: bool,
62
+ status: int | None = None,
63
+ wait: float | None = None,
64
+ ) -> None:
65
+ """Make the error; `certain` as the class says, `status` the HTTP status the service answered, if it did.
66
+
67
+ `wait` is how long its reply asked to be left before the next try, from its `Retry-After`, if it named one.
68
+ """
69
+ super().__init__(message)
70
+ self.certain = certain
71
+ self.status = status
72
+ self.wait = wait
73
+ #: How many times the request was tried before it was given up on, a try that never left among them.
74
+ self.tries = 1
75
+
76
+
77
+ class RefusedError(HttpError):
78
+ """The service refused it: a 4xx, or a redirect, which is never followed. It is `certain`."""
79
+
80
+
81
+ class RateLimitedError(RefusedError):
82
+ """The service refused it for now: a 429, or a 403 naming `Retry-After`, as GitHub's secondary rate limit is."""
83
+
84
+
85
+ class NotSentError(HttpError):
86
+ """The request never left: no connection could be made to the service. It is `certain`."""
87
+
88
+
89
+ class UntrustedError(HttpError):
90
+ """No connection was made: the service's certificate is not one the system trusts. It is `certain`.
91
+
92
+ Sending again would not change that, so it is not sent again.
93
+ """
94
+
95
+
96
+ class FailedError(HttpError):
97
+ """The service may have carried it out: it answered with a server error, or its reply broke off or is not JSON.
98
+
99
+ So is a success whose JSON its caller's `failed` reads as a failure of the service's own.
100
+ """
101
+
102
+
103
+ class TimedOutError(HttpError):
104
+ """The service did not answer in time. It may have carried the request out."""
105
+
106
+
107
+ @dataclass(frozen=True)
108
+ class Retry:
109
+ """When a request is sent again."""
110
+
111
+ #: The pause before each new try: one try, then one more for each pause.
112
+ pauses: Sequence[float] = (1.0, 3.0)
113
+ #: The longest `Retry-After` a refusal may ask for and be waited out; one asking longer is the refusal it is.
114
+ longest_wait: float = 10.0
115
+ #: How far each pause is moved at random, as a share of it either way, from 0 to 1: half by default, so a pause of
116
+ #: 1 second is one of 0.5 to 1.5. Programs that failed together, as at an outage, then do not all try again at once.
117
+ #: A `Retry-After` is only ever moved later, never cut short.
118
+ jitter: float = 0.5
119
+
120
+ def __post_init__(self) -> None:
121
+ """Refuse a jitter outside 0 to 1, which could draw a pause below none.
122
+
123
+ Raises:
124
+ ValueError: `jitter` is below 0 or above 1.
125
+ """
126
+ if not 0.0 <= self.jitter <= 1.0:
127
+ msg = f"jitter must be from 0 to 1, not {self.jitter}"
128
+ raise ValueError(msg)
129
+
130
+
131
+ @dataclass(frozen=True)
132
+ class Reply:
133
+ """The service's answer to one request, a 2xx."""
134
+
135
+ status: int
136
+ #: The whole reply, decoded, with what is not UTF-8 replaced.
137
+ text: str
138
+ #: Whether it is a web page (HTML), as a service's error pages are: naming one says more than quoting it.
139
+ page: bool
140
+
141
+
142
+ class Client:
143
+ """A service at one origin, with the headers each request carries, its credentials among them.
144
+
145
+ A request goes to that origin alone: a URL naming another is refused before it is sent, and a redirect is never
146
+ followed. Each request opens a connection of its own, so one the service closed while idle is never reused.
147
+ """
148
+
149
+ def __init__(
150
+ self,
151
+ origin: str,
152
+ *,
153
+ name: str,
154
+ headers: Mapping[str, str] | None = None,
155
+ retry: Retry | None = None,
156
+ ) -> None:
157
+ """Talk to `origin`, a URL whose path is ignored, as `name`, such as `GitHub`, in what errors say.
158
+
159
+ Raises:
160
+ ValueError: `origin` is not an http or https URL.
161
+ """
162
+ parts = urllib.parse.urlsplit(origin)
163
+ if parts.scheme not in {"https", "http"} or not parts.netloc:
164
+ raise ValueError(f"{origin!r} is not an http or https URL")
165
+ self.origin = f"{parts.scheme}://{parts.netloc}"
166
+ self.name = name
167
+ self._headers = dict(headers or {})
168
+ self._retry = retry or Retry()
169
+ self._ssl: ssl.SSLContext = httpx2.create_ssl_context()
170
+
171
+ def send(
172
+ self,
173
+ method: str,
174
+ url: str,
175
+ *,
176
+ body: object = None,
177
+ params: Mapping[str, str] | None = None,
178
+ headers: Mapping[str, str] | None = None,
179
+ again: bool = False,
180
+ ) -> Reply:
181
+ """Send one request to `url`, a path or a URL at the client's origin, with `body` as JSON if it is given.
182
+
183
+ `again` is whether it may be sent again though the service may have carried it out, as a read may be.
184
+
185
+ Returns:
186
+ The service's 2xx reply.
187
+
188
+ Raises:
189
+ ValueError: `url` is at another origin.
190
+ HttpError: The request failed, each time it was sent.
191
+ """
192
+ request = self._request(method, url, body=body, params=params, headers=headers, defaults={})
193
+ return self._retrying(request, again=again, read=lambda reply: reply)
194
+
195
+ def json(
196
+ self,
197
+ method: str,
198
+ url: str,
199
+ *,
200
+ body: object = None,
201
+ params: Mapping[str, str] | None = None,
202
+ headers: Mapping[str, str] | None = None,
203
+ again: bool = False,
204
+ failed: Callable[[object], str | None] | None = None,
205
+ ) -> object:
206
+ """Send one request as `send` does, whose reply must be JSON: one that is not fails the try, as a page does.
207
+
208
+ `failed` reads the parsed reply and names a failure the service reports in a success, as GitHub's GraphQL API
209
+ does for a query it could not run; that try fails as a server error does, so `again` sends it again.
210
+
211
+ Returns:
212
+ The reply, parsed.
213
+
214
+ Raises:
215
+ ValueError: `url` is at another origin.
216
+ HttpError: The request failed, or its reply was not JSON, each time it was sent.
217
+ """
218
+ request = self._request(
219
+ method,
220
+ url,
221
+ body=body,
222
+ params=params,
223
+ headers=headers,
224
+ defaults={"Accept": "application/json"},
225
+ )
226
+ return self._retrying(request, again=again, read=lambda reply: self._parse(reply, failed))
227
+
228
+ def _retrying[T](self, request: httpx2.Request, *, again: bool, read: Callable[[Reply], T]) -> T:
229
+ """Send `request` and `read` its reply, and again after each pause while what went wrong allows it.
230
+
231
+ Returns:
232
+ What `read` makes of the service's 2xx reply.
233
+
234
+ Raises:
235
+ HttpError: It failed, or `read` raised one, each time it was sent; its `tries` says how many times.
236
+ """
237
+ pauses = list(self._retry.pauses)
238
+ tries = 0
239
+ while True:
240
+ tries += 1
241
+ try:
242
+ return read(self._once(request))
243
+ except HttpError as e:
244
+ wait = self._wait(e, pauses, again=again)
245
+ if wait is None:
246
+ e.tries = tries
247
+ raise
248
+ time.sleep(wait)
249
+
250
+ def _request(
251
+ self,
252
+ method: str,
253
+ url: str,
254
+ *,
255
+ body: object,
256
+ params: Mapping[str, str] | None,
257
+ headers: Mapping[str, str] | None,
258
+ defaults: Mapping[str, str],
259
+ ) -> httpx2.Request:
260
+ """Build the request, refusing a URL at another origin, so a credential in its headers goes nowhere else.
261
+
262
+ Its headers are `defaults`, then the client's, then `headers`, each overriding the one before.
263
+
264
+ Returns:
265
+ The request.
266
+
267
+ Raises:
268
+ ValueError: `url` is at another origin.
269
+ """
270
+ target = urllib.parse.urljoin(self.origin + "/", url)
271
+ parts = urllib.parse.urlsplit(target)
272
+ if f"{parts.scheme}://{parts.netloc}" != self.origin:
273
+ raise ValueError(f"{url!r} is not at {self.origin}")
274
+ merged = {"User-Agent": "canopy", **defaults, **self._headers, **(headers or {})}
275
+ content = None if body is None else json.dumps(body).encode()
276
+ if content is not None:
277
+ merged.setdefault("Content-Type", "application/json")
278
+ return httpx2.Request(method, target, params=dict(params or {}), headers=merged, content=content)
279
+
280
+ def _once(self, request: httpx2.Request) -> Reply:
281
+ """Send `request` once, on a connection of its own.
282
+
283
+ Returns:
284
+ The service's 2xx reply.
285
+
286
+ Raises:
287
+ RefusedError: It answered with a refusal or a redirect.
288
+ RateLimitedError: It refused it for now, as a rate limit does.
289
+ NotSentError: No connection could be made.
290
+ UntrustedError: The service's certificate is not trusted.
291
+ FailedError: It answered with a server error, or the connection broke before its reply came whole.
292
+ TimedOutError: It did not answer in time.
293
+ """
294
+ timeout = httpx2.Timeout(TIMEOUT_SECONDS, connect=CONNECT_SECONDS)
295
+ try:
296
+ with httpx2.Client(verify=self._ssl, timeout=timeout, follow_redirects=False) as client:
297
+ response = client.send(request)
298
+ except (httpx2.ConnectError, httpx2.ConnectTimeout, httpx2.ProxyError) as e:
299
+ if _untrusted(e):
300
+ raise UntrustedError(f"{self.origin}'s certificate is not trusted: {e}", certain=True) from e
301
+ raise NotSentError(f"cannot reach {self.origin}: {e}", certain=True) from e
302
+ except httpx2.TimeoutException as e:
303
+ raise TimedOutError(f"{self.name} did not answer in time: {e!r}", certain=False) from e
304
+ except httpx2.TransportError as e:
305
+ # A reply cut off, a connection reset or closed with no reply, or one that is not HTTP.
306
+ raise FailedError(f"the connection to {self.origin} broke: {e!r}", certain=False) from e
307
+ page = "html" in response.headers.get("Content-Type", "")
308
+ text = response.content.decode(errors="replace")
309
+ if response.is_success:
310
+ return Reply(response.status_code, text, page)
311
+ quote = f"{self.name}'s error page" if page else text[:MAX_QUOTE]
312
+ message = f"HTTP {response.status_code}: {quote}"
313
+ status, wait = response.status_code, _retry_after(response)
314
+ if status >= 500: # noqa: PLR2004
315
+ # A server error may come after the request was carried out; a refusal comes before.
316
+ raise FailedError(message, certain=False, status=status, wait=wait)
317
+ if status == _TOO_MANY or (status in _WAIT_STATUSES and wait is not None):
318
+ raise RateLimitedError(message, certain=True, status=status, wait=wait)
319
+ raise RefusedError(message, certain=True, status=status)
320
+
321
+ def _parse(self, reply: Reply, failed: Callable[[object], str | None] | None) -> object:
322
+ """`reply` as JSON, which `failed`, if given, finds no failure in.
323
+
324
+ Returns:
325
+ It, parsed.
326
+
327
+ Raises:
328
+ FailedError: It is not JSON, as a service's error page answered with a 200 is not, or `failed` named one.
329
+ """
330
+ try:
331
+ parsed: object = json.loads(reply.text)
332
+ except json.JSONDecodeError as e:
333
+ quote = f"{self.name}'s error page" if reply.page else reply.text[:MAX_QUOTE]
334
+ raise FailedError(f"{self.name}'s reply is not JSON: {quote}", certain=False, status=reply.status) from e
335
+ why = None if failed is None else failed(parsed)
336
+ if why is not None:
337
+ raise FailedError(why, certain=False, status=reply.status)
338
+ return parsed
339
+
340
+ def _wait(self, error: HttpError, pauses: list[float], *, again: bool) -> float | None:
341
+ """How long to wait before sending again after `error`, taking a pause from `pauses`; None to send no more.
342
+
343
+ Returns:
344
+ The seconds to wait, or None.
345
+ """
346
+ if not pauses or (error.wait is not None and error.wait > self._retry.longest_wait):
347
+ return None
348
+ # Sent again whatever it asks: it cannot have been carried out. A timeout is never sent again.
349
+ harmless = isinstance(error, NotSentError | RateLimitedError)
350
+ if not harmless and not (again and isinstance(error, FailedError)):
351
+ return None
352
+ spread = self._retry.jitter
353
+ # Not a secret: a pause moved at random so that tries spread out.
354
+ drawn = random.uniform(1.0 - spread, 1.0 + spread) # noqa: S311
355
+ # The wait a refusal asked for is moved too, so clients it refused together do not all try again at once, but
356
+ # only later: never shorter than it asked.
357
+ return max(pauses.pop(0) * drawn, (error.wait or 0.0) * max(drawn, 1.0))
358
+
359
+
360
+ def _untrusted(error: BaseException) -> bool:
361
+ """Whether `error` came of a certificate the system does not trust, as the TLS error it was raised from says.
362
+
363
+ Returns:
364
+ Whether it did.
365
+ """
366
+ seen: BaseException | None = error
367
+ for _ in range(_MAX_CHAIN):
368
+ if seen is None:
369
+ return False
370
+ if isinstance(seen, ssl.SSLCertVerificationError):
371
+ return True
372
+ seen = seen.__cause__ or seen.__context__
373
+ return False
374
+
375
+
376
+ def _retry_after(response: httpx2.Response) -> float | None:
377
+ """The wait a reply's `Retry-After` names, in seconds or as a date; None when it names none.
378
+
379
+ Returns:
380
+ The seconds, never below zero, or None.
381
+ """
382
+ value = response.headers.get("Retry-After", "").strip()
383
+ if not value:
384
+ return None
385
+ if value.isascii() and value.isdigit():
386
+ return float(value)
387
+ try:
388
+ when = email.utils.parsedate_to_datetime(value)
389
+ except (TypeError, ValueError):
390
+ return None
391
+ if when.tzinfo is None:
392
+ when = when.replace(tzinfo=UTC)
393
+ return max((when - datetime.now(UTC)).total_seconds(), 0.0)
@@ -0,0 +1,69 @@
1
+ Metadata-Version: 2.5
2
+ Name: eddieland-canopy-http
3
+ Version: 0.14.0
4
+ Summary: canopy's HTTP client for the programs it ships: one origin, no redirects, and retries only where safe.
5
+ Project-URL: Homepage, https://github.com/eddieland/canopy
6
+ Project-URL: Repository, https://github.com/eddieland/canopy/tree/main/packages/canopy-http
7
+ Project-URL: Issues, https://github.com/eddieland/canopy/issues
8
+ Author: eddieland
9
+ License-Expression: MIT
10
+ Keywords: canopy,client,http
11
+ Classifier: Development Status :: 2 - Pre-Alpha
12
+ Classifier: Environment :: Console
13
+ Classifier: Intended Audience :: Developers
14
+ Classifier: Operating System :: MacOS
15
+ Classifier: Operating System :: POSIX :: Linux
16
+ Classifier: Programming Language :: Python :: 3
17
+ Classifier: Programming Language :: Python :: 3 :: Only
18
+ Classifier: Programming Language :: Python :: 3.12
19
+ Classifier: Topic :: Internet :: WWW/HTTP
20
+ Requires-Python: >=3.12
21
+ Requires-Dist: httpx2>=2.16.2
22
+ Description-Content-Type: text/markdown
23
+
24
+ # canopy-http
25
+
26
+ The HTTP client the programs canopy ships use for every request they make (D130): the GitHub programs
27
+ (`canopy-github`), the Jira connector (`canopy-jira`), and the Slack sink and its reader (`canopy-notify-slack`). It
28
+ is a library, with no command of its own, and imports nothing from canopy. The harness never uses it: it opens no
29
+ connection and holds no token (TRUST_MODEL T2).
30
+
31
+ ```python
32
+ import canopy_http
33
+
34
+ client = canopy_http.Client("https://api.github.com", name="GitHub", headers={"Authorization": f"Bearer {token}"})
35
+ data = client.json("POST", "/graphql", body={"query": QUERY}, again=True)
36
+ ```
37
+
38
+ What it promises:
39
+
40
+ - **One origin.** A `Client` is bound to the origin it is made with. A URL naming another is refused before it is
41
+ sent, and a redirect is never followed, so a credential in its headers goes nowhere else.
42
+
43
+ - **The system's certificates**, so an Enterprise host with its own CA works, and the environment's proxy
44
+ (`HTTPS_PROXY`) and certificates (`SSL_CERT_FILE`).
45
+
46
+ - **One account of what went wrong.** Every failure of a request is an `HttpError`, and its `certain` says whether
47
+ the request is known not to have been carried out, so a caller knows whether sending it again could do it twice. A
48
+ caller's own mistake, an origin that is not an http or https URL or a URL at another origin, is a `ValueError`,
49
+ raised before anything is sent:
50
+
51
+ | Error | When | `certain` |
52
+ | ------------------ | -------------------------------------------------------- | --------- |
53
+ | `RefusedError` | a 4xx, or a redirect | yes |
54
+ | `RateLimitedError` | a 429, or a 403 naming `Retry-After` | yes |
55
+ | `NotSentError` | no connection could be made | yes |
56
+ | `UntrustedError` | the service's certificate is not one the system trusts | yes |
57
+ | `FailedError` | a server error; a reply cut off, not JSON, or `failed` | no |
58
+ | `TimedOutError` | no answer in time | no |
59
+
60
+ - **Retries only where safe.** A request is sent again, after each of `Retry.pauses`, when that cannot do it twice:
61
+ it never left, or the service refused it and said how long to wait, for no longer than `Retry.longest_wait`. One
62
+ sent with `again=True`, as a read is, is also sent again after a failure that may have been carried out. A timed-out
63
+ request is never sent again. Each pause is moved at random by up to `Retry.jitter` of it, half by default, so
64
+ programs that failed together do not all try again at once; a wait the service asked for is never cut short. The
65
+ error given up on says in `tries` how many times the request was tried.
66
+
67
+ `send` returns the 2xx `Reply`; `json` asks for JSON and returns it parsed. Its `failed`, if given, reads the parsed
68
+ reply and names a failure the service reports in a 2xx, as GitHub's GraphQL API does for a query it could not run:
69
+ that try raises `FailedError`, so `again=True` sends it again. httpx2 is the transport.
@@ -0,0 +1,4 @@
1
+ canopy_http/__init__.py,sha256=7oRY6r2wZ4R5UFDVXQ3O3pm213pQkrCYdvkyJA9nzFs,16506
2
+ eddieland_canopy_http-0.14.0.dist-info/METADATA,sha256=FHl0UheXvOeoFZvudqPKNNQhmCpfYtf4c6JwJWzRCyU,4098
3
+ eddieland_canopy_http-0.14.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
4
+ eddieland_canopy_http-0.14.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.33.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any