eddieland-canopy-http 0.14.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
|
@@ -0,0 +1,243 @@
|
|
|
1
|
+
# Byte-compiled / optimized / DLL files
|
|
2
|
+
__pycache__/
|
|
3
|
+
*.py[codz]
|
|
4
|
+
*$py.class
|
|
5
|
+
|
|
6
|
+
# C extensions
|
|
7
|
+
*.so
|
|
8
|
+
|
|
9
|
+
# Distribution / packaging
|
|
10
|
+
.Python
|
|
11
|
+
build/
|
|
12
|
+
develop-eggs/
|
|
13
|
+
dist/
|
|
14
|
+
downloads/
|
|
15
|
+
eggs/
|
|
16
|
+
.eggs/
|
|
17
|
+
lib/
|
|
18
|
+
lib64/
|
|
19
|
+
# The web UI's own lib/ is source, not a build directory.
|
|
20
|
+
!ui/src/lib/
|
|
21
|
+
parts/
|
|
22
|
+
sdist/
|
|
23
|
+
var/
|
|
24
|
+
wheels/
|
|
25
|
+
share/python-wheels/
|
|
26
|
+
*.egg-info/
|
|
27
|
+
.installed.cfg
|
|
28
|
+
*.egg
|
|
29
|
+
MANIFEST
|
|
30
|
+
|
|
31
|
+
# PyInstaller
|
|
32
|
+
# Usually these files are written by a python script from a template
|
|
33
|
+
# before PyInstaller builds the exe, so as to inject date/other infos into it.
|
|
34
|
+
*.manifest
|
|
35
|
+
*.spec
|
|
36
|
+
|
|
37
|
+
# Installer logs
|
|
38
|
+
pip-log.txt
|
|
39
|
+
pip-delete-this-directory.txt
|
|
40
|
+
|
|
41
|
+
# Unit test / coverage reports
|
|
42
|
+
htmlcov/
|
|
43
|
+
.tox/
|
|
44
|
+
.nox/
|
|
45
|
+
.coverage
|
|
46
|
+
.coverage.*
|
|
47
|
+
.cache
|
|
48
|
+
nosetests.xml
|
|
49
|
+
coverage.xml
|
|
50
|
+
*.cover
|
|
51
|
+
*.py.cover
|
|
52
|
+
.hypothesis/
|
|
53
|
+
.pytest_cache/
|
|
54
|
+
cover/
|
|
55
|
+
|
|
56
|
+
# Translations
|
|
57
|
+
*.mo
|
|
58
|
+
*.pot
|
|
59
|
+
|
|
60
|
+
# Django stuff:
|
|
61
|
+
*.log
|
|
62
|
+
local_settings.py
|
|
63
|
+
db.sqlite3
|
|
64
|
+
db.sqlite3-journal
|
|
65
|
+
|
|
66
|
+
# Flask stuff:
|
|
67
|
+
instance/
|
|
68
|
+
.webassets-cache
|
|
69
|
+
|
|
70
|
+
# Scrapy stuff:
|
|
71
|
+
.scrapy
|
|
72
|
+
|
|
73
|
+
# Sphinx documentation
|
|
74
|
+
docs/_build/
|
|
75
|
+
|
|
76
|
+
# PyBuilder
|
|
77
|
+
.pybuilder/
|
|
78
|
+
target/
|
|
79
|
+
|
|
80
|
+
# Jupyter Notebook
|
|
81
|
+
.ipynb_checkpoints
|
|
82
|
+
|
|
83
|
+
# IPython
|
|
84
|
+
profile_default/
|
|
85
|
+
ipython_config.py
|
|
86
|
+
|
|
87
|
+
# pyenv
|
|
88
|
+
# For a library or package, you might want to ignore these files since the code is
|
|
89
|
+
# intended to run in multiple environments; otherwise, check them in:
|
|
90
|
+
# .python-version
|
|
91
|
+
|
|
92
|
+
# pipenv
|
|
93
|
+
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
|
|
94
|
+
# However, in case of collaboration, if having platform-specific dependencies or dependencies
|
|
95
|
+
# having no cross-platform support, pipenv may install dependencies that don't work, or not
|
|
96
|
+
# install all needed dependencies.
|
|
97
|
+
# Pipfile.lock
|
|
98
|
+
|
|
99
|
+
# UV
|
|
100
|
+
# Similar to Pipfile.lock, it is generally recommended to include uv.lock in version control.
|
|
101
|
+
# This is especially recommended for binary packages to ensure reproducibility, and is more
|
|
102
|
+
# commonly ignored for libraries.
|
|
103
|
+
# uv.lock
|
|
104
|
+
|
|
105
|
+
# poetry
|
|
106
|
+
# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
|
|
107
|
+
# This is especially recommended for binary packages to ensure reproducibility, and is more
|
|
108
|
+
# commonly ignored for libraries.
|
|
109
|
+
# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
|
|
110
|
+
# poetry.lock
|
|
111
|
+
# poetry.toml
|
|
112
|
+
|
|
113
|
+
# pdm
|
|
114
|
+
# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
|
|
115
|
+
# pdm recommends including project-wide configuration in pdm.toml, but excluding .pdm-python.
|
|
116
|
+
# https://pdm-project.org/en/latest/usage/project/#working-with-version-control
|
|
117
|
+
# pdm.lock
|
|
118
|
+
# pdm.toml
|
|
119
|
+
.pdm-python
|
|
120
|
+
.pdm-build/
|
|
121
|
+
|
|
122
|
+
# pixi
|
|
123
|
+
# Similar to Pipfile.lock, it is generally recommended to include pixi.lock in version control.
|
|
124
|
+
# pixi.lock
|
|
125
|
+
# Pixi creates a virtual environment in the .pixi directory, just like venv module creates one
|
|
126
|
+
# in the .venv directory. It is recommended not to include this directory in version control.
|
|
127
|
+
.pixi
|
|
128
|
+
|
|
129
|
+
# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
|
|
130
|
+
__pypackages__/
|
|
131
|
+
|
|
132
|
+
# Celery stuff
|
|
133
|
+
celerybeat-schedule
|
|
134
|
+
celerybeat.pid
|
|
135
|
+
|
|
136
|
+
# Redis
|
|
137
|
+
*.rdb
|
|
138
|
+
*.aof
|
|
139
|
+
*.pid
|
|
140
|
+
|
|
141
|
+
# RabbitMQ
|
|
142
|
+
mnesia/
|
|
143
|
+
rabbitmq/
|
|
144
|
+
rabbitmq-data/
|
|
145
|
+
|
|
146
|
+
# ActiveMQ
|
|
147
|
+
activemq-data/
|
|
148
|
+
|
|
149
|
+
# SageMath parsed files
|
|
150
|
+
*.sage.py
|
|
151
|
+
|
|
152
|
+
# Environments
|
|
153
|
+
.env
|
|
154
|
+
.envrc
|
|
155
|
+
.venv
|
|
156
|
+
env/
|
|
157
|
+
venv/
|
|
158
|
+
ENV/
|
|
159
|
+
env.bak/
|
|
160
|
+
venv.bak/
|
|
161
|
+
|
|
162
|
+
# Spyder project settings
|
|
163
|
+
.spyderproject
|
|
164
|
+
.spyproject
|
|
165
|
+
|
|
166
|
+
# Rope project settings
|
|
167
|
+
.ropeproject
|
|
168
|
+
|
|
169
|
+
# mkdocs documentation
|
|
170
|
+
/site
|
|
171
|
+
|
|
172
|
+
# mypy
|
|
173
|
+
.mypy_cache/
|
|
174
|
+
.dmypy.json
|
|
175
|
+
dmypy.json
|
|
176
|
+
|
|
177
|
+
# Pyre type checker
|
|
178
|
+
.pyre/
|
|
179
|
+
|
|
180
|
+
# pytype static type analyzer
|
|
181
|
+
.pytype/
|
|
182
|
+
|
|
183
|
+
# Cython debug symbols
|
|
184
|
+
cython_debug/
|
|
185
|
+
|
|
186
|
+
# PyCharm
|
|
187
|
+
# JetBrains specific template is maintained in a separate JetBrains.gitignore that can
|
|
188
|
+
# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
|
|
189
|
+
# and can be added to the global gitignore or merged into this file. For a more nuclear
|
|
190
|
+
# option (not recommended) you can uncomment the following to ignore the entire idea folder.
|
|
191
|
+
# .idea/
|
|
192
|
+
|
|
193
|
+
# Abstra
|
|
194
|
+
# Abstra is an AI-powered process automation framework.
|
|
195
|
+
# Ignore directories containing user credentials, local state, and settings.
|
|
196
|
+
# Learn more at https://abstra.io/docs
|
|
197
|
+
.abstra/
|
|
198
|
+
|
|
199
|
+
# Visual Studio Code
|
|
200
|
+
# Visual Studio Code specific template is maintained in a separate VisualStudioCode.gitignore
|
|
201
|
+
# that can be found at https://github.com/github/gitignore/blob/main/Global/VisualStudioCode.gitignore
|
|
202
|
+
# and can be added to the global gitignore or merged into this file. However, if you prefer,
|
|
203
|
+
# you could uncomment the following to ignore the entire vscode folder
|
|
204
|
+
# .vscode/
|
|
205
|
+
# Temporary file for partial code execution
|
|
206
|
+
tempCodeRunnerFile.py
|
|
207
|
+
|
|
208
|
+
# Ruff stuff:
|
|
209
|
+
.ruff_cache/
|
|
210
|
+
|
|
211
|
+
# PyPI configuration file
|
|
212
|
+
.pypirc
|
|
213
|
+
|
|
214
|
+
# Marimo
|
|
215
|
+
marimo/_static/
|
|
216
|
+
marimo/_lsp/
|
|
217
|
+
__marimo__/
|
|
218
|
+
|
|
219
|
+
# Streamlit
|
|
220
|
+
.streamlit/secrets.toml
|
|
221
|
+
|
|
222
|
+
# Impeccable (.claude/skills/impeccable): its runtime state and per-developer files. Shared artifacts stay tracked:
|
|
223
|
+
# config.json, live/config.json, design.json, surfaces/*.md, critique/*.md. The engine binary downloads to
|
|
224
|
+
# ~/.impeccable/bin, or sits beside the launcher in scripts/bin.
|
|
225
|
+
.claude/skills/impeccable/scripts/bin/
|
|
226
|
+
**/.impeccable/config.local.json
|
|
227
|
+
**/.impeccable/hook.cache.json
|
|
228
|
+
**/.impeccable/hook.pending.json
|
|
229
|
+
**/.impeccable/*.png
|
|
230
|
+
**/.impeccable/review/
|
|
231
|
+
**/.impeccable/questions/
|
|
232
|
+
**/.impeccable/history/
|
|
233
|
+
**/.impeccable/live/server.json
|
|
234
|
+
**/.impeccable/live/sessions/
|
|
235
|
+
**/.impeccable/live/previews/
|
|
236
|
+
**/.impeccable/live/annotations/
|
|
237
|
+
**/.impeccable/live/cache/
|
|
238
|
+
**/.impeccable/live/manual-edit-apply-transaction.json
|
|
239
|
+
**/.impeccable/live/manual-edit-events.jsonl
|
|
240
|
+
**/.impeccable/live/manual-edit-evidence/
|
|
241
|
+
**/.impeccable/live/pending-manual-edits.json
|
|
242
|
+
**/.impeccable/live/deferred-svelte-component-accepts.json
|
|
243
|
+
**/.impeccable/live/*.png
|
|
@@ -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,46 @@
|
|
|
1
|
+
# canopy-http
|
|
2
|
+
|
|
3
|
+
The HTTP client the programs canopy ships use for every request they make (D130): the GitHub programs
|
|
4
|
+
(`canopy-github`), the Jira connector (`canopy-jira`), and the Slack sink and its reader (`canopy-notify-slack`). It
|
|
5
|
+
is a library, with no command of its own, and imports nothing from canopy. The harness never uses it: it opens no
|
|
6
|
+
connection and holds no token (TRUST_MODEL T2).
|
|
7
|
+
|
|
8
|
+
```python
|
|
9
|
+
import canopy_http
|
|
10
|
+
|
|
11
|
+
client = canopy_http.Client("https://api.github.com", name="GitHub", headers={"Authorization": f"Bearer {token}"})
|
|
12
|
+
data = client.json("POST", "/graphql", body={"query": QUERY}, again=True)
|
|
13
|
+
```
|
|
14
|
+
|
|
15
|
+
What it promises:
|
|
16
|
+
|
|
17
|
+
- **One origin.** A `Client` is bound to the origin it is made with. A URL naming another is refused before it is
|
|
18
|
+
sent, and a redirect is never followed, so a credential in its headers goes nowhere else.
|
|
19
|
+
|
|
20
|
+
- **The system's certificates**, so an Enterprise host with its own CA works, and the environment's proxy
|
|
21
|
+
(`HTTPS_PROXY`) and certificates (`SSL_CERT_FILE`).
|
|
22
|
+
|
|
23
|
+
- **One account of what went wrong.** Every failure of a request is an `HttpError`, and its `certain` says whether
|
|
24
|
+
the request is known not to have been carried out, so a caller knows whether sending it again could do it twice. A
|
|
25
|
+
caller's own mistake, an origin that is not an http or https URL or a URL at another origin, is a `ValueError`,
|
|
26
|
+
raised before anything is sent:
|
|
27
|
+
|
|
28
|
+
| Error | When | `certain` |
|
|
29
|
+
| ------------------ | -------------------------------------------------------- | --------- |
|
|
30
|
+
| `RefusedError` | a 4xx, or a redirect | yes |
|
|
31
|
+
| `RateLimitedError` | a 429, or a 403 naming `Retry-After` | yes |
|
|
32
|
+
| `NotSentError` | no connection could be made | yes |
|
|
33
|
+
| `UntrustedError` | the service's certificate is not one the system trusts | yes |
|
|
34
|
+
| `FailedError` | a server error; a reply cut off, not JSON, or `failed` | no |
|
|
35
|
+
| `TimedOutError` | no answer in time | no |
|
|
36
|
+
|
|
37
|
+
- **Retries only where safe.** A request is sent again, after each of `Retry.pauses`, when that cannot do it twice:
|
|
38
|
+
it never left, or the service refused it and said how long to wait, for no longer than `Retry.longest_wait`. One
|
|
39
|
+
sent with `again=True`, as a read is, is also sent again after a failure that may have been carried out. A timed-out
|
|
40
|
+
request is never sent again. Each pause is moved at random by up to `Retry.jitter` of it, half by default, so
|
|
41
|
+
programs that failed together do not all try again at once; a wait the service asked for is never cut short. The
|
|
42
|
+
error given up on says in `tries` how many times the request was tried.
|
|
43
|
+
|
|
44
|
+
`send` returns the 2xx `Reply`; `json` asks for JSON and returns it parsed. Its `failed`, if given, reads the parsed
|
|
45
|
+
reply and names a failure the service reports in a 2xx, as GitHub's GraphQL API does for a query it could not run:
|
|
46
|
+
that try raises `FailedError`, so `again=True` sends it again. httpx2 is the transport.
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
[project]
|
|
2
|
+
# Its name on PyPI, where every package canopy ships takes the same prefix (D046). Its programs and modules keep
|
|
3
|
+
# theirs.
|
|
4
|
+
name = "eddieland-canopy-http"
|
|
5
|
+
# From the latest v* tag, as canopy's is (D085), so every package canopy ships carries its version.
|
|
6
|
+
dynamic = ["version"]
|
|
7
|
+
description = "canopy's HTTP client for the programs it ships: one origin, no redirects, and retries only where safe."
|
|
8
|
+
readme = "README.md"
|
|
9
|
+
license = "MIT"
|
|
10
|
+
authors = [{ name = "eddieland" }]
|
|
11
|
+
keywords = ["canopy", "http", "client"]
|
|
12
|
+
classifiers = [
|
|
13
|
+
"Development Status :: 2 - Pre-Alpha",
|
|
14
|
+
"Environment :: Console",
|
|
15
|
+
"Intended Audience :: Developers",
|
|
16
|
+
"Operating System :: MacOS",
|
|
17
|
+
"Operating System :: POSIX :: Linux",
|
|
18
|
+
"Programming Language :: Python :: 3",
|
|
19
|
+
"Programming Language :: Python :: 3 :: Only",
|
|
20
|
+
"Programming Language :: Python :: 3.12",
|
|
21
|
+
"Topic :: Internet :: WWW/HTTP",
|
|
22
|
+
]
|
|
23
|
+
requires-python = ">=3.12"
|
|
24
|
+
# httpx2 for its transport: it tells a request that never left from one that may have been carried out, and trusts
|
|
25
|
+
# the system's certificates (truststore), so an Enterprise host's own CA works. Nothing from canopy.
|
|
26
|
+
dependencies = ["httpx2>=2.16.2"]
|
|
27
|
+
|
|
28
|
+
[project.urls]
|
|
29
|
+
Homepage = "https://github.com/eddieland/canopy"
|
|
30
|
+
Repository = "https://github.com/eddieland/canopy/tree/main/packages/canopy-http"
|
|
31
|
+
Issues = "https://github.com/eddieland/canopy/issues"
|
|
32
|
+
|
|
33
|
+
[build-system]
|
|
34
|
+
requires = ["hatchling", "uv-dynamic-versioning==0.14.1"]
|
|
35
|
+
build-backend = "hatchling.build"
|
|
36
|
+
|
|
37
|
+
[tool.hatch.version]
|
|
38
|
+
source = "uv-dynamic-versioning"
|
|
39
|
+
|
|
40
|
+
# The same scheme as canopy's, in the root pyproject.toml.
|
|
41
|
+
[tool.uv-dynamic-versioning]
|
|
42
|
+
vcs = "git"
|
|
43
|
+
style = "pep440"
|
|
44
|
+
bump = true
|
|
45
|
+
fallback-version = "0.0.0"
|
|
46
|
+
|
|
47
|
+
# The version is built from git, so a new commit or tag rebuilds the metadata, not only a changed pyproject.toml.
|
|
48
|
+
[tool.uv]
|
|
49
|
+
cache-keys = [{ file = "pyproject.toml" }, { git = { commit = true, tags = true } }]
|
|
50
|
+
|
|
51
|
+
[tool.hatch.build.targets.wheel]
|
|
52
|
+
packages = ["src/canopy_http"]
|
|
@@ -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)
|