github-statistics 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.
Files changed (86) hide show
  1. github_statistics/__init__.py +14 -0
  2. github_statistics/__main__.py +10 -0
  3. github_statistics/_version.py +24 -0
  4. github_statistics/cli/__init__.py +9 -0
  5. github_statistics/cli/app.py +104 -0
  6. github_statistics/cli/cache.py +159 -0
  7. github_statistics/cli/collect.py +219 -0
  8. github_statistics/cli/common.py +128 -0
  9. github_statistics/cli/config.py +80 -0
  10. github_statistics/cli/doctor.py +214 -0
  11. github_statistics/cli/export.py +111 -0
  12. github_statistics/cli/options.py +175 -0
  13. github_statistics/cli/render.py +126 -0
  14. github_statistics/cli/run.py +137 -0
  15. github_statistics/cli/scope.py +96 -0
  16. github_statistics/cli/site.py +150 -0
  17. github_statistics/client/__init__.py +40 -0
  18. github_statistics/client/accounting.py +99 -0
  19. github_statistics/client/budget.py +125 -0
  20. github_statistics/client/cooldown.py +113 -0
  21. github_statistics/client/errors.py +60 -0
  22. github_statistics/client/graphql.py +281 -0
  23. github_statistics/client/paging.py +92 -0
  24. github_statistics/client/policy.py +243 -0
  25. github_statistics/client/transport.py +437 -0
  26. github_statistics/collect/__init__.py +44 -0
  27. github_statistics/collect/common.py +69 -0
  28. github_statistics/collect/enrich_items.py +423 -0
  29. github_statistics/collect/items.py +238 -0
  30. github_statistics/collect/jobs.py +194 -0
  31. github_statistics/collect/listed.py +42 -0
  32. github_statistics/collect/members.py +70 -0
  33. github_statistics/collect/reader.py +124 -0
  34. github_statistics/collect/run.py +354 -0
  35. github_statistics/collect/runs.py +436 -0
  36. github_statistics/collect/slices.py +55 -0
  37. github_statistics/collect/steps.py +154 -0
  38. github_statistics/collect/sweep.py +70 -0
  39. github_statistics/config/__init__.py +37 -0
  40. github_statistics/config/loader.py +430 -0
  41. github_statistics/config/models.py +156 -0
  42. github_statistics/config/schema.py +245 -0
  43. github_statistics/export/__init__.py +11 -0
  44. github_statistics/export/csv.py +93 -0
  45. github_statistics/export/documents.py +189 -0
  46. github_statistics/export/json.py +33 -0
  47. github_statistics/py.typed +2 -0
  48. github_statistics/render/__init__.py +44 -0
  49. github_statistics/render/bars3d.py +420 -0
  50. github_statistics/render/charts.py +214 -0
  51. github_statistics/render/demo.py +133 -0
  52. github_statistics/render/images.py +31 -0
  53. github_statistics/render/layout.py +341 -0
  54. github_statistics/render/model.py +260 -0
  55. github_statistics/render/palette.py +41 -0
  56. github_statistics/scope/__init__.py +17 -0
  57. github_statistics/scope/apply.py +95 -0
  58. github_statistics/scope/resolver.py +228 -0
  59. github_statistics/series/__init__.py +22 -0
  60. github_statistics/series/actors.py +128 -0
  61. github_statistics/series/coverage.py +86 -0
  62. github_statistics/series/daily.py +229 -0
  63. github_statistics/series/leaderboard.py +221 -0
  64. github_statistics/series/repositories.py +154 -0
  65. github_statistics/site/__init__.py +9 -0
  66. github_statistics/site/assets/site.css +281 -0
  67. github_statistics/site/build.py +392 -0
  68. github_statistics/site/templates/base.html.j2 +25 -0
  69. github_statistics/site/templates/index.html.j2 +30 -0
  70. github_statistics/site/templates/macros.html.j2 +5 -0
  71. github_statistics/site/templates/site.js.j2 +66 -0
  72. github_statistics/site/templates/target.html.j2 +95 -0
  73. github_statistics/store/__init__.py +40 -0
  74. github_statistics/store/activity.py +311 -0
  75. github_statistics/store/aggregates.py +294 -0
  76. github_statistics/store/base.py +163 -0
  77. github_statistics/store/codec.py +263 -0
  78. github_statistics/store/models.py +136 -0
  79. github_statistics/store/paths.py +36 -0
  80. github_statistics/store/schema.py +169 -0
  81. github_statistics/store/sqlite.py +299 -0
  82. github_statistics-0.1.0.dist-info/METADATA +308 -0
  83. github_statistics-0.1.0.dist-info/RECORD +86 -0
  84. github_statistics-0.1.0.dist-info/WHEEL +4 -0
  85. github_statistics-0.1.0.dist-info/entry_points.txt +2 -0
  86. github_statistics-0.1.0.dist-info/licenses/LICENSE +201 -0
@@ -0,0 +1,243 @@
1
+ # SPDX-License-Identifier: Apache-2.0
2
+ # SPDX-FileCopyrightText: 2026 The Linux Foundation
3
+ """The transport's request policy: URLs, headers, retries and redirects."""
4
+
5
+ from __future__ import annotations
6
+
7
+ import math
8
+ import re
9
+ import time
10
+ from collections.abc import Mapping
11
+ from typing import Any
12
+
13
+ import httpx
14
+
15
+ # Redirects a REST ``GET`` follows.
16
+ REDIRECT_STATUSES = frozenset({301, 302, 303, 307, 308})
17
+
18
+ # Seconds to wait out a first secondary rate limit that names no retry
19
+ # time, as GitHub's documentation asks; each retry after it doubles.
20
+ SECONDARY_WAIT = 60.0
21
+
22
+ # Failures raised before the request left, so GitHub charged nothing.
23
+ UNSENT = (httpx.ConnectError, httpx.ConnectTimeout, httpx.PoolTimeout)
24
+
25
+ # GraphQL's lexical grammar: ignored tokens (a byte order mark, white
26
+ # space, line terminators, commas and comments), block and plain strings,
27
+ # names, and any other character as a punctuator of its own.
28
+ _GRAPHQL_TOKEN = re.compile(
29
+ r"(?P<ignored>(?:[\ufeff\t\n\r ,]|#[^\r\n]*)+)"
30
+ r'|(?P<string>"""(?:\\"""|(?!""")[\s\S])*"""|"(?:\\.|[^"\\\r\n])*")'
31
+ r"|(?P<name>[_A-Za-z][_0-9A-Za-z]*)"
32
+ r"|(?P<other>[\s\S])"
33
+ )
34
+ _WRITE_OPERATIONS = frozenset({"mutation", "subscription"})
35
+
36
+
37
+ def graphql_url(api_url: str) -> str:
38
+ """The GraphQL endpoint for the REST base ``api_url``.
39
+
40
+ ``https://api.github.com`` answers GraphQL at ``/graphql``; a GitHub
41
+ Enterprise Server base ending ``/api/v3`` answers at ``/api/graphql``.
42
+ """
43
+ base = api_url.rstrip("/")
44
+ if base.endswith("/api/v3"):
45
+ return base[: -len("/v3")] + "/graphql"
46
+ return base + "/graphql"
47
+
48
+
49
+ def parse_retry_after(value: str | None) -> float | None:
50
+ """Seconds from a ``Retry-After`` header, or ``None`` when it does not parse.
51
+
52
+ Only the delay-seconds form is read: GitHub sends no other, and the
53
+ HTTP-date form would need the current time.
54
+ """
55
+ if value is None:
56
+ return None
57
+ try:
58
+ seconds = float(value.strip())
59
+ except ValueError:
60
+ return None
61
+ if not math.isfinite(seconds) or seconds < 0:
62
+ return None
63
+ return seconds
64
+
65
+
66
+ def int_header(response: httpx.Response, name: str) -> int | None:
67
+ """Header ``name`` as an integer, or ``None`` when absent or malformed."""
68
+ value = response.headers.get(name)
69
+ if value is None:
70
+ return None
71
+ try:
72
+ return int(value)
73
+ except ValueError:
74
+ return None
75
+
76
+
77
+ def origin(url: httpx.URL) -> tuple[str, str, int | None]:
78
+ """Scheme, host and effective port of ``url``."""
79
+ port = url.port
80
+ if port is None:
81
+ port = {"https": 443, "http": 80}.get(url.scheme)
82
+ return url.scheme, url.host, port
83
+
84
+
85
+ def names_secondary_limit(message: Any) -> bool:
86
+ """Whether ``message`` says GitHub applied a secondary rate limit."""
87
+ return isinstance(message, str) and "secondary rate limit" in message.lower()
88
+
89
+
90
+ def errors_name_secondary(errors: list[Any]) -> bool:
91
+ """Whether a GraphQL error list names a secondary rate limit."""
92
+ return any(
93
+ isinstance(error, dict) and names_secondary_limit(error.get("message"))
94
+ for error in errors
95
+ )
96
+
97
+
98
+ def _primary_error(error: Any) -> bool:
99
+ """Whether one GraphQL error reports a primary rate limit.
100
+
101
+ GitHub marks one ``type: RATE_LIMITED``, or ``type: RATE_LIMIT``
102
+ with ``extensions.code: graphql_rate_limit``, often with ``data: null``.
103
+ """
104
+ if not isinstance(error, dict):
105
+ return False
106
+ extensions = error.get("extensions")
107
+ code = extensions.get("code") if isinstance(extensions, dict) else None
108
+ return error.get("type") in ("RATE_LIMITED", "RATE_LIMIT") or (
109
+ code == "graphql_rate_limit"
110
+ )
111
+
112
+
113
+ def errors_rate_limited(errors: list[Any]) -> bool:
114
+ """Whether a GraphQL error list reports a rate limit, primary or secondary.
115
+
116
+ A secondary limit may carry only a message naming it, even in an
117
+ HTTP ``200``.
118
+ """
119
+ return any(map(_primary_error, errors)) or errors_name_secondary(errors)
120
+
121
+
122
+ def secondary_body(response: httpx.Response) -> bool:
123
+ """Whether a ``403`` or ``429`` names a secondary rate limit in its body.
124
+
125
+ GitHub may answer a secondary rate limit with neither ``Retry-After``
126
+ nor ``x-ratelimit-remaining: 0``; its message, documentation link or
127
+ an error message still names the limit. A primary ``RATE_LIMITED``
128
+ error does not, so it stops only its own resource.
129
+ """
130
+ if response.status_code not in (403, 429):
131
+ return False
132
+ try:
133
+ body = response.json()
134
+ except ValueError:
135
+ return False
136
+ if not isinstance(body, dict):
137
+ return False
138
+ link = body.get("documentation_url")
139
+ errors = body.get("errors")
140
+ return (
141
+ names_secondary_limit(body.get("message"))
142
+ or (isinstance(link, str) and "secondary-rate-limits" in link)
143
+ or (isinstance(errors, list) and errors_name_secondary(errors))
144
+ )
145
+
146
+
147
+ def rate_limited(response: httpx.Response) -> bool:
148
+ """Whether ``response`` is a rate limit.
149
+
150
+ A ``429`` is; so is a ``403`` carrying ``Retry-After`` or
151
+ ``x-ratelimit-remaining: 0``, or whose body names a secondary rate
152
+ limit. Any other ``403`` is a permission error.
153
+ """
154
+ status = response.status_code
155
+ return status == 429 or (
156
+ status == 403
157
+ and (
158
+ "retry-after" in response.headers
159
+ or response.headers.get("x-ratelimit-remaining") == "0"
160
+ or secondary_body(response)
161
+ )
162
+ )
163
+
164
+
165
+ def rate_limit_delay(response: httpx.Response, backoff: float) -> float:
166
+ """Seconds to wait out rate-limited ``response``, given the exponential ``backoff``.
167
+
168
+ ``Retry-After`` wins when it parses; then, with
169
+ ``x-ratelimit-remaining: 0``, the time until its ``x-ratelimit-reset``
170
+ epoch, or none once it has passed; a body naming a secondary limit
171
+ with no retry time scales ``backoff``, which doubles from one second,
172
+ from ``SECONDARY_WAIT``: 60, 120, then 240 seconds; anything else
173
+ takes ``backoff``.
174
+ """
175
+ after = parse_retry_after(response.headers.get("retry-after"))
176
+ if after is not None:
177
+ return after
178
+ reset = int_header(response, "x-ratelimit-reset")
179
+ if response.headers.get("x-ratelimit-remaining") == "0" and reset is not None:
180
+ return max(reset - time.time(), 0.0)
181
+ if secondary_body(response):
182
+ return SECONDARY_WAIT * backoff
183
+ return backoff
184
+
185
+
186
+ def secondary_limit(response: httpx.Response) -> bool:
187
+ """Whether the rate limit ``response`` reports may be a secondary one.
188
+
189
+ A body naming a secondary limit is one, whatever the headers say.
190
+ Otherwise only a primary limit reports ``x-ratelimit-remaining: 0``,
191
+ and it bounds one resource; a secondary limit spans every API the
192
+ token reaches, so any other rate limit is treated as one.
193
+ """
194
+ return (
195
+ secondary_body(response) or response.headers.get("x-ratelimit-remaining") != "0"
196
+ )
197
+
198
+
199
+ def write_operation(query: str) -> str | None:
200
+ """The ``mutation`` or ``subscription`` keyword opening a definition in ``query``.
201
+
202
+ Returns ``None`` for a document of queries and fragments. Comments,
203
+ commas and string literals are skipped, and brackets are counted, so
204
+ a keyword only counts at the start of a top-level definition. This
205
+ guards the read-only client against misuse; it is not a security
206
+ boundary, and a malformed document is left for GitHub to reject.
207
+ """
208
+ depth = 0
209
+ at_definition = True
210
+ for token in _GRAPHQL_TOKEN.finditer(query):
211
+ kind, text = token.lastgroup, token.group()
212
+ if kind in ("ignored", "string"):
213
+ continue
214
+ if at_definition and text in _WRITE_OPERATIONS:
215
+ return text
216
+ at_definition = False
217
+ if text in ("{", "(", "["):
218
+ depth += 1
219
+ elif text in ("}", ")", "]"):
220
+ depth = max(depth - 1, 0)
221
+ at_definition = text == "}" and depth == 0
222
+ return None
223
+
224
+
225
+ def retry_kind(response: httpx.Response) -> str | None:
226
+ """Why ``response`` should be retried, or ``None`` to return it.
227
+
228
+ The client only reads, so every rate limit and ``5xx`` is safe to resend.
229
+ """
230
+ if rate_limited(response):
231
+ return "rate_limit"
232
+ if response.status_code >= 500:
233
+ return "server"
234
+ return None
235
+
236
+
237
+ def with_params(url: httpx.URL, params: Mapping[str, Any] | None) -> httpx.URL:
238
+ """``url`` with ``params`` merged into its query; ``params`` wins a shared key.
239
+
240
+ ``httpx`` replaces a URL's query with ``params`` rather than merging
241
+ them, which would silently drop a filter such as ``?state=all``.
242
+ """
243
+ return url.copy_merge_params(params) if params else url
@@ -0,0 +1,437 @@
1
+ # SPDX-License-Identifier: Apache-2.0
2
+ # SPDX-FileCopyrightText: 2026 The Linux Foundation
3
+ """The one HTTP transport every GitHub request goes through (design §4.1).
4
+
5
+ ``Transport`` owns authentication, the concurrency limit, the retry and
6
+ backoff policy, redirects, request accounting and the budget charge. The
7
+ token goes only to the configured API host, over HTTPS unless the caller
8
+ opts out, and is never logged.
9
+
10
+ The client is read-only by construction (design §9.4): it sends a REST
11
+ ``GET`` through ``request()`` and a GraphQL query, a ``POST`` to the
12
+ GraphQL endpoint, through ``graphql()``, and nothing else. ``request()``
13
+ refuses any other method and ``graphql()`` refuses a mutation or a
14
+ subscription, both before sending. Every request is therefore safe to
15
+ resend, and one retry rule covers them all.
16
+ """
17
+
18
+ from __future__ import annotations
19
+
20
+ import asyncio
21
+ import logging
22
+ from collections.abc import Awaitable, Callable, Mapping
23
+ from dataclasses import dataclass
24
+ from types import TracebackType
25
+ from typing import Any
26
+
27
+ import httpx
28
+
29
+ from .accounting import Ledger, RequestStats
30
+ from .budget import DEFAULT_ANONYMOUS_RESERVE, DEFAULT_RESERVE, Budget
31
+ from .cooldown import ALL, Cooldown
32
+ from .errors import AuthError, BudgetExhaustedError, ForeignHostError, TransportError
33
+ from .policy import (
34
+ REDIRECT_STATUSES,
35
+ UNSENT,
36
+ graphql_url,
37
+ origin,
38
+ rate_limit_delay,
39
+ retry_kind,
40
+ secondary_limit,
41
+ with_params,
42
+ )
43
+
44
+ log = logging.getLogger(__name__)
45
+
46
+ DEFAULT_API_URL = "https://api.github.com"
47
+ API_VERSION = "2022-11-28"
48
+ USER_AGENT = "github-statistics"
49
+ MAX_WAIT = 120.0
50
+ FIRST_BACKOFF = 1.0
51
+ MAX_REDIRECTS = 5
52
+
53
+ Sleep = Callable[[float], Awaitable[None]]
54
+
55
+
56
+ @dataclass(frozen=True)
57
+ class _Call:
58
+ """One request: a REST ``GET``, or a GraphQL query ``POST`` with its body."""
59
+
60
+ target: httpx.URL
61
+ headers: dict[str, str]
62
+ json: Any = None
63
+ graphql: bool = False
64
+
65
+ @property
66
+ def method(self) -> str:
67
+ """``POST`` for a GraphQL query, ``GET`` for anything else."""
68
+ return "POST" if self.graphql else "GET"
69
+
70
+
71
+ @dataclass
72
+ class _Progress:
73
+ """Retries and waiting spent on one request, across all its redirect hops."""
74
+
75
+ retries: int = 0
76
+ waited: float = 0.0
77
+ sent: bool = False
78
+
79
+
80
+ class Transport:
81
+ """An async context manager over one ``httpx.AsyncClient``.
82
+
83
+ Every request, a REST ``GET`` or a GraphQL query, applies this policy:
84
+
85
+ - a transport failure retries with exponential backoff, then raises
86
+ ``TransportError``;
87
+ - a ``401`` raises ``AuthError`` at once, without a retry, and stops
88
+ the transport: every queued or later attempt raises it unsent;
89
+ - a rate limit (``policy.rate_limited``) backs off as
90
+ ``policy.rate_limit_delay`` says, pausing every other attempt for
91
+ its resource, or every resource for a possibly secondary limit,
92
+ until the backoff ends, even if the request is cancelled; one that
93
+ outlasts the retries stops that resource, or every resource, for
94
+ the run, and every later attempt on it raises
95
+ ``BudgetExhaustedError`` unsent;
96
+ - any ``5xx`` retries on the same schedule;
97
+ - a ``GET``'s ``301``, ``302``, ``303``, ``307`` or ``308`` is
98
+ followed, up to ``MAX_REDIRECTS`` hops, when its ``Location``
99
+ shares the API origin, and refused otherwise; any other redirect,
100
+ and any redirect of a GraphQL query, returns unfollowed;
101
+ - anything else returns to the caller, including a ``403`` that is a
102
+ real permission error.
103
+
104
+ Backoff starts at one second and doubles, for at most ``max_retries``
105
+ retries and ``max_wait`` seconds of total waiting per request, its
106
+ redirect hops together. When retries run out on a response, that
107
+ last response returns to the caller, unless it is a rate limit and
108
+ the transport has a budget. Every response discarded for a retry or
109
+ a redirect is closed.
110
+
111
+ With a ``Budget``, which belongs to this transport alone, every
112
+ chargeable attempt, retries and redirect hops included, reserves one
113
+ REST request before it is sent and raises ``BudgetExhaustedError``
114
+ when none is left; a retry that could not be sent raises it before
115
+ backing off. So does every final rate-limit response, closed first,
116
+ so the collector stops cleanly and keeps its partial coverage. A
117
+ rate-limited GraphQL query retries like any other request; when
118
+ retries run out it raises it and stops the GraphQL budget, and a
119
+ GraphQL attempt checks that stop once it holds a connection slot,
120
+ and raises it unsent.
121
+ """
122
+
123
+ def __init__(
124
+ self,
125
+ token: str | None,
126
+ *,
127
+ api_url: str = DEFAULT_API_URL,
128
+ concurrency: int = 8,
129
+ max_retries: int = 5,
130
+ timeout: float = 30.0,
131
+ budget: Budget | None = None,
132
+ sleep: Sleep = asyncio.sleep,
133
+ max_wait: float = MAX_WAIT,
134
+ insecure: bool = False,
135
+ ) -> None:
136
+ """Configure the transport; ``sleep`` is injectable so tests run instantly.
137
+
138
+ A token travels over HTTPS alone: an ``api_url`` with any other
139
+ scheme raises ``ValueError`` unless ``insecure`` opts in.
140
+ """
141
+ if concurrency < 1:
142
+ raise ValueError(f"concurrency must be at least 1, not {concurrency}")
143
+ if token is not None and not insecure and httpx.URL(api_url).scheme != "https":
144
+ raise ValueError(f"refusing to send a token to non-HTTPS {api_url!r}")
145
+ self.api_url = api_url.rstrip("/")
146
+ self.graphql_url = graphql_url(self.api_url)
147
+ self.budget = budget
148
+ self.max_retries = max_retries
149
+ self.max_wait = max_wait
150
+ self._token = token
151
+ self._rejected = False
152
+ self._origin = origin(httpx.URL(self.api_url))
153
+ self._cooldown = Cooldown(httpx.URL(self.api_url).path)
154
+ if budget is not None and budget.reserve is None:
155
+ budget.reserve = (
156
+ DEFAULT_RESERVE if token is not None else DEFAULT_ANONYMOUS_RESERVE
157
+ )
158
+ self._ledger = Ledger(budget, authenticated=token is not None)
159
+ self.stats: RequestStats = self._ledger.stats
160
+ self._sleep = sleep
161
+ self._semaphore = asyncio.Semaphore(concurrency)
162
+ self._client = httpx.AsyncClient(
163
+ timeout=timeout,
164
+ follow_redirects=False,
165
+ headers={
166
+ "Accept": "application/vnd.github+json",
167
+ "X-GitHub-Api-Version": API_VERSION,
168
+ "User-Agent": USER_AGENT,
169
+ },
170
+ )
171
+
172
+ def __repr__(self) -> str:
173
+ """Name the API host only; never the token."""
174
+ return f"Transport(api_url={self.api_url!r})"
175
+
176
+ async def __aenter__(self) -> Transport:
177
+ """Enter the context; the client is already open."""
178
+ return self
179
+
180
+ async def __aexit__(
181
+ self,
182
+ exc_type: type[BaseException] | None,
183
+ exc: BaseException | None,
184
+ tb: TracebackType | None,
185
+ ) -> None:
186
+ """Close the client and its connection pool."""
187
+ await self.aclose()
188
+
189
+ async def aclose(self) -> None:
190
+ """Close the client and its connection pool, ending any pause."""
191
+ self._cooldown.close()
192
+ await self._client.aclose()
193
+
194
+ def stop(self, secondary: bool, resource: str = "graphql") -> None:
195
+ """Stop ``resource``, or every resource if ``secondary``, for the run."""
196
+ self._cooldown.stop(ALL if secondary else resource)
197
+
198
+ @property
199
+ def rest_left(self) -> int | None:
200
+ """REST requests this transport may still spend, if budgeted."""
201
+ if self.budget is None:
202
+ return None
203
+ return self.budget.rest_left
204
+
205
+ @property
206
+ def rest_exhausted(self) -> bool:
207
+ """True once the budget has no REST request left."""
208
+ return self.rest_left == 0
209
+
210
+ def resolve(self, url: str) -> httpx.URL:
211
+ """``url`` made absolute against ``api_url``; refuses any other host.
212
+
213
+ A path joins ``api_url``. An absolute URL, such as one from a
214
+ ``Link`` header, must share the scheme, host and port of
215
+ ``api_url``, so neither a header nor a crafted URL can send the
216
+ token elsewhere.
217
+ """
218
+ if url.startswith(("http://", "https://")):
219
+ target = httpx.URL(url)
220
+ else:
221
+ target = httpx.URL(self.api_url + "/" + url.lstrip("/"))
222
+ if origin(target) != self._origin:
223
+ raise ForeignHostError(
224
+ f"refusing a request to {target.host!r}: the API host is "
225
+ f"{self._origin[1]!r}"
226
+ )
227
+ return target
228
+
229
+ async def request(
230
+ self,
231
+ method: str,
232
+ url: str,
233
+ *,
234
+ params: Mapping[str, Any] | None = None,
235
+ headers: Mapping[str, str] | None = None,
236
+ charge: bool = True,
237
+ ) -> httpx.Response:
238
+ """Issue one REST ``GET`` under the retry policy and return its response.
239
+
240
+ ``method`` must be ``GET``: the client is read-only, so any other
241
+ method raises ``ValueError`` before anything is sent. ``params``
242
+ merge into any query ``url`` carries. ``charge=False`` keeps the
243
+ request off the REST budget (for the free ``GET /rate_limit``), and
244
+ an authenticated ``304`` is refunded.
245
+ """
246
+ if method.upper() != "GET":
247
+ raise ValueError(f"the client is read-only; refusing {method} {url}")
248
+ target = with_params(self.resolve(url), params)
249
+ call = _Call(target, self._headers(headers))
250
+ return await self._follow(call, charge, _Progress())
251
+
252
+ async def _post_graphql(self, body: Any, estimate: int) -> httpx.Response:
253
+ """Post one query for ``graphql()``, holding ``estimate`` points first.
254
+
255
+ Raises ``AuthError`` after a ``401``, before taking any points, and
256
+ ``BudgetExhaustedError`` when they are not left. The query stays off
257
+ the REST budget, and its points come back if no attempt left. A
258
+ redirect returns unfollowed: GitHub does not redirect its GraphQL
259
+ endpoint.
260
+ """
261
+ self._refuse_rejected("POST /graphql")
262
+ budget = self.budget
263
+ if budget is not None and not budget.try_spend_graphql(estimate):
264
+ raise BudgetExhaustedError(
265
+ f"no GraphQL budget left for a query costing {estimate}"
266
+ )
267
+ target = self.resolve(self.graphql_url)
268
+ call = _Call(target, self._headers(None), body, graphql=True)
269
+ progress = _Progress()
270
+ try:
271
+ return await self._retrying(call, True, progress)
272
+ except BaseException:
273
+ if budget is not None and not progress.sent:
274
+ budget.settle_graphql(estimate, 0)
275
+ raise
276
+
277
+ def _headers(self, headers: Mapping[str, str] | None) -> dict[str, str]:
278
+ """``headers`` with the token, for a URL ``resolve`` has accepted."""
279
+ sent = dict(headers or {})
280
+ if self._token is not None:
281
+ sent["Authorization"] = f"Bearer {self._token}"
282
+ return sent
283
+
284
+ async def _follow(
285
+ self, call: _Call, charge: bool, progress: _Progress
286
+ ) -> httpx.Response:
287
+ """Send a ``GET``, following same-origin redirects up to ``MAX_REDIRECTS``."""
288
+ hops = 0
289
+ while True:
290
+ response = await self._retrying(call, charge, progress)
291
+ location = response.headers.get("location")
292
+ if (
293
+ response.status_code not in REDIRECT_STATUSES
294
+ or location is None
295
+ or hops >= MAX_REDIRECTS
296
+ ):
297
+ return response
298
+ await response.aclose()
299
+ call = _Call(self.resolve(str(call.target.join(location))), call.headers)
300
+ hops += 1
301
+ log.debug("following %s to %s", response.status_code, call.target.path)
302
+
303
+ async def _retrying(
304
+ self, call: _Call, charge: bool, progress: _Progress
305
+ ) -> httpx.Response:
306
+ """Send ``call`` under the retry policy, spending from ``progress``."""
307
+ method, target = call.method, call.target
308
+ budget = self.budget
309
+ chargeable = charge and budget is not None and not call.graphql
310
+ resource = self._cooldown.resource(target, call.graphql)
311
+ while True:
312
+ retries, waited = progress.retries, progress.waited
313
+ delay = FIRST_BACKOFF * 2**retries
314
+ scope = resource
315
+ discard: httpx.Response | None = None
316
+ try:
317
+ response = await self._attempt(call, chargeable, progress)
318
+ except httpx.TransportError as exc:
319
+ if retries >= self.max_retries or waited + delay > self.max_wait:
320
+ raise TransportError(
321
+ f"{method} {target.copy_with(query=None)} failed after "
322
+ f"{retries} retries: {type(exc).__name__}"
323
+ ) from exc
324
+ kind = "transport"
325
+ else:
326
+ if response.status_code == 401:
327
+ await response.aclose()
328
+ raise AuthError(
329
+ f"GitHub rejected the token (401) for {method} {target.path}"
330
+ )
331
+ why = retry_kind(response)
332
+ if why is None:
333
+ return response
334
+ kind = why
335
+ if kind == "rate_limit":
336
+ delay = rate_limit_delay(response, delay)
337
+ scope = ALL if secondary_limit(response) else resource
338
+ final = retries >= self.max_retries or waited + delay > self.max_wait
339
+ if kind == "rate_limit" and final:
340
+ self._cooldown.stop(scope)
341
+ if budget is not None:
342
+ await response.aclose()
343
+ if call.graphql:
344
+ budget.exhaust_graphql()
345
+ raise BudgetExhaustedError(
346
+ f"rate limited past the retries for {method} {target.path}"
347
+ )
348
+ if final:
349
+ return response
350
+ discard = response
351
+ # Paused before the first await, so no queued attempt slips past.
352
+ pause = None
353
+ if kind == "rate_limit":
354
+ pause = self._cooldown.pause(scope, self._sleep(delay))
355
+ if discard is not None:
356
+ await discard.aclose()
357
+ if chargeable and self.rest_exhausted:
358
+ raise BudgetExhaustedError(
359
+ f"no REST budget left to retry {method} {target.path}"
360
+ )
361
+ progress.retries += 1
362
+ progress.waited += delay
363
+ self.stats.retries[kind] += 1
364
+ log.debug("retrying %s %s in %.1fs (%s)", method, target.path, delay, kind)
365
+ await (self._sleep(delay) if pause is None else asyncio.shield(pause))
366
+
367
+ def _refuse_rejected(self, label: str) -> None:
368
+ """Raise ``AuthError`` once GitHub has rejected this transport's token."""
369
+ if self._rejected:
370
+ raise AuthError(f"GitHub rejected the token earlier; not sending {label}")
371
+
372
+ async def _attempt(
373
+ self, call: _Call, chargeable: bool, progress: _Progress
374
+ ) -> httpx.Response:
375
+ """Send one attempt, reserving its REST request first when ``chargeable``.
376
+
377
+ It waits out a rate-limit pause on its resource before taking a
378
+ connection slot, and gives the slot back to wait again if a pause
379
+ began meanwhile, so a paused resource never blocks another's
380
+ traffic. Once it holds a slot, an attempt raises unsent after a
381
+ ``401`` on this transport, and raises ``BudgetExhaustedError``
382
+ unsent once a terminal rate limit has stopped its resource, or
383
+ for a query once GraphQL is stopped.
384
+ """
385
+ label = f"{call.method} {call.target.path}"
386
+ resource = self._cooldown.resource(call.target, call.graphql)
387
+ while True:
388
+ await self._cooldown.wait(resource)
389
+ await self._semaphore.acquire()
390
+ if not self._cooldown.held(resource):
391
+ break
392
+ self._semaphore.release()
393
+ try:
394
+ self._refuse_rejected(label)
395
+ budget = self.budget
396
+ if self._cooldown.stopped(resource) or (
397
+ call.graphql and budget is not None and budget.graphql_stopped
398
+ ):
399
+ raise BudgetExhaustedError(
400
+ f"the {resource} rate limit is spent; not sending {label}"
401
+ )
402
+ self._ledger.reserve(label, rest=chargeable)
403
+ self.stats.requests += 1
404
+ try:
405
+ response = await self._client.request(
406
+ call.method, call.target, json=call.json, headers=call.headers
407
+ )
408
+ except UNSENT:
409
+ self._ledger.refund(rest=chargeable)
410
+ raise
411
+ except BaseException:
412
+ progress.sent = True
413
+ raise
414
+ progress.sent = True
415
+ if response.status_code == 401:
416
+ self._rejected = True
417
+ finally:
418
+ self._semaphore.release()
419
+ self._ledger.record(response, graphql=call.graphql, rest=chargeable)
420
+ return response
421
+
422
+ async def seed_budget(self) -> None:
423
+ """Seed the budget from ``GET /rate_limit``, which costs nothing.
424
+
425
+ A server without rate limiting (some GitHub Enterprise Server
426
+ installs answer ``404``) leaves the budget unseeded; any other
427
+ failure raises ``httpx.HTTPStatusError``, and a success with no
428
+ core count raises ``ClientError``, since collecting with an
429
+ unknown reserve could drain the token.
430
+ """
431
+ if self.budget is None:
432
+ return
433
+ response = await self.request("GET", "/rate_limit", charge=False)
434
+ if response.status_code == 404:
435
+ return
436
+ response.raise_for_status()
437
+ self._ledger.seed(response, response.json())