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,125 @@
1
+ # SPDX-License-Identifier: Apache-2.0
2
+ # SPDX-FileCopyrightText: 2026 The Linux Foundation
3
+ """The request budget of one target's run (design §6.5).
4
+
5
+ The budget is a courtesy limit, not exact accounting: GitHub enforces
6
+ the real rate limit, and the transport backs off on it. The budget lets
7
+ a run stop cleanly and leave headroom for other consumers. Nothing here
8
+ raises; the transport raises ``BudgetExhaustedError`` when a reservation
9
+ is refused, and a collector that meets it stops cleanly.
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ from dataclasses import dataclass
15
+
16
+ DEFAULT_REST = 3000
17
+ DEFAULT_GRAPHQL_POINTS = 1500
18
+ DEFAULT_RESERVE = 500
19
+ # GitHub allows an anonymous client 60 core requests an hour.
20
+ DEFAULT_ANONYMOUS_RESERVE = 10
21
+
22
+
23
+ @dataclass
24
+ class Budget:
25
+ """REST requests and GraphQL points one transport may still spend.
26
+
27
+ One ``Budget`` belongs to one ``Transport``: one token, one target.
28
+ ``rest`` caps the REST requests and ``graphql_points`` the GraphQL
29
+ points of that target's run. ``reserve`` is what the token keeps of
30
+ ``x-ratelimit-remaining`` for other consumers; left at ``None``, the
31
+ transport sets ``DEFAULT_RESERVE`` for a token and
32
+ ``DEFAULT_ANONYMOUS_RESERVE`` for anonymous reads.
33
+
34
+ Tolerance: the observed ``remaining`` only moves when a response
35
+ reports it, so a run may overshoot ``rest``, or dip into the
36
+ reserve, by at most the transport's concurrency (requests already in
37
+ flight), and may overshoot ``graphql_points`` by at most the queries
38
+ in flight. A response without a core ``x-ratelimit-remaining`` header
39
+ leaves the observed count where it was; while GitHub sends none, only
40
+ ``rest`` bounds the run. Exactness beyond that is a non-goal.
41
+
42
+ A GraphQL rate limit stops the GraphQL budget for the rest of the
43
+ run: ``graphql_stopped`` is never cleared, so a query that settles
44
+ afterwards cannot reopen it.
45
+ """
46
+
47
+ rest: int = DEFAULT_REST
48
+ graphql_points: int = DEFAULT_GRAPHQL_POINTS
49
+ reserve: int | None = None
50
+ rest_spent: int = 0
51
+ graphql_spent: int = 0
52
+ remaining: int | None = None
53
+ reset: int | None = None
54
+ graphql_stopped: bool = False
55
+
56
+ def observe(self, remaining: int, reset: int | None = None) -> None:
57
+ """Take the core ``remaining`` count of the window ending ``reset``.
58
+
59
+ Within one window the lowest count wins, since responses arrive
60
+ out of order; a later ``reset`` starts a new window and replaces
61
+ the count, and an earlier one is stale and ignored.
62
+ """
63
+ if self.remaining is None or (
64
+ reset is not None and self.reset is not None and reset > self.reset
65
+ ):
66
+ self.remaining, self.reset = remaining, reset
67
+ elif reset is None or self.reset is None or reset == self.reset:
68
+ self.remaining = min(self.remaining, remaining)
69
+ self.reset = self.reset if reset is None else reset
70
+
71
+ def try_spend_rest(self) -> bool:
72
+ """Take one REST request before it is sent; false when none is left."""
73
+ if self.rest_left == 0:
74
+ return False
75
+ self.rest_spent += 1
76
+ return True
77
+
78
+ def refund_rest(self) -> None:
79
+ """Give back one REST request GitHub did not charge."""
80
+ self.rest_spent = max(self.rest_spent - 1, 0)
81
+
82
+ def try_spend_graphql(self, estimate: int) -> bool:
83
+ """Take ``estimate`` GraphQL points before a query; false when not left."""
84
+ estimate = max(estimate, 0)
85
+ if self.graphql_exhausted or self.graphql_left < estimate:
86
+ return False
87
+ self.graphql_spent += estimate
88
+ return True
89
+
90
+ def settle_graphql(self, estimate: int, actual: int | None) -> None:
91
+ """Replace a query's ``estimate`` with its ``actual`` cost, when known."""
92
+ if actual is not None:
93
+ self.graphql_spent = max(
94
+ self.graphql_spent - max(estimate, 0) + max(actual, 0), 0
95
+ )
96
+
97
+ def exhaust_graphql(self) -> None:
98
+ """Stop GraphQL for the run, after GitHub rate-limited a query."""
99
+ self.graphql_stopped = True
100
+
101
+ @property
102
+ def rest_left(self) -> int:
103
+ """REST requests left: the allowance, less the reserve once observed."""
104
+ left = max(self.rest - self.rest_spent, 0)
105
+ if self.remaining is None:
106
+ return left
107
+ reserve = DEFAULT_RESERVE if self.reserve is None else self.reserve
108
+ return min(left, max(0, self.remaining - reserve))
109
+
110
+ @property
111
+ def graphql_left(self) -> int:
112
+ """GraphQL points left to spend; none once GraphQL is stopped."""
113
+ if self.graphql_stopped:
114
+ return 0
115
+ return max(self.graphql_points - self.graphql_spent, 0)
116
+
117
+ @property
118
+ def rest_exhausted(self) -> bool:
119
+ """True once no REST request is left."""
120
+ return self.rest_left == 0
121
+
122
+ @property
123
+ def graphql_exhausted(self) -> bool:
124
+ """True once no GraphQL point is left."""
125
+ return self.graphql_left == 0
@@ -0,0 +1,113 @@
1
+ # SPDX-License-Identifier: Apache-2.0
2
+ # SPDX-FileCopyrightText: 2026 The Linux Foundation
3
+ """A rate-limit pause that every request for the same resource waits out."""
4
+
5
+ from __future__ import annotations
6
+
7
+ import asyncio
8
+ from collections.abc import Awaitable
9
+
10
+ import httpx
11
+
12
+ # The key that pauses or stops every resource at once: a secondary rate
13
+ # limit spans REST and GraphQL alike.
14
+ ALL = "*"
15
+
16
+
17
+ class Cooldown:
18
+ """Which rate-limit resources a transport is backing off from.
19
+
20
+ While a rate limit's backoff (its ``Retry-After``, or the request's
21
+ own backoff) runs, the resource it drew on, ``core``, ``search`` or
22
+ ``graphql``, or ``ALL`` for a secondary limit, is paused: every
23
+ attempt for it, queued or a retry, waits until the backoff ends
24
+ rather than sending into the limit. The pause belongs to the limit,
25
+ not to the request that met it, so it runs to its end even when
26
+ that request is cancelled. That wait is not counted against the
27
+ waiting request's own wait budget; the pause it waits on is bounded
28
+ by the backoff of the request that met the limit.
29
+
30
+ A rate limit that outlasts a request's retries stops its resource,
31
+ or ``ALL``, for the rest of the run: ``stopped`` stays true, so no
32
+ later attempt sends into a limit already known to hold.
33
+ """
34
+
35
+ def __init__(self, base_path: str) -> None:
36
+ """Track pauses for an API whose paths start with ``base_path``."""
37
+ self._base = base_path.rstrip("/")
38
+ self._holders: dict[str, int] = {}
39
+ self._open: dict[str, asyncio.Event] = {}
40
+ self._stopped: set[str] = set()
41
+ self._pauses: set[asyncio.Future[None]] = set()
42
+
43
+ def resource(self, target: httpx.URL, graphql: bool) -> str:
44
+ """The rate-limit resource a request to ``target`` draws on."""
45
+ if graphql:
46
+ return "graphql"
47
+ path = target.path
48
+ if path.startswith(self._base + "/"):
49
+ path = path[len(self._base) :]
50
+ return "search" if path.startswith("/search/") else "core"
51
+
52
+ def _event(self, key: str) -> asyncio.Event:
53
+ """The event that is set while ``key`` is not paused."""
54
+ event = self._open.get(key)
55
+ if event is None:
56
+ event = self._open[key] = asyncio.Event()
57
+ event.set()
58
+ return event
59
+
60
+ def pause(self, key: str, backoff: Awaitable[None]) -> asyncio.Future[None]:
61
+ """Pause ``key`` from now until ``backoff`` finishes, and return it.
62
+
63
+ The pause starts before this returns, so no queued attempt slips
64
+ past, and ``backoff`` runs as a task of its own: a caller that
65
+ awaits it through ``asyncio.shield`` can be cancelled without
66
+ ending the pause early.
67
+ """
68
+ self._holders[key] = self._holders.get(key, 0) + 1
69
+ self._event(key).clear()
70
+ task = asyncio.ensure_future(backoff)
71
+ self._pauses.add(task)
72
+
73
+ def release(done: asyncio.Future[None]) -> None:
74
+ self._pauses.discard(done)
75
+ self._holders[key] -= 1
76
+ if not self._holders[key]:
77
+ self._event(key).set()
78
+
79
+ task.add_done_callback(release)
80
+ return task
81
+
82
+ def _holding(self, resource: str) -> str | None:
83
+ """The key whose pause holds ``resource`` now, if any."""
84
+ for key in (ALL, resource):
85
+ if self._holders.get(key):
86
+ return key
87
+ return None
88
+
89
+ def held(self, resource: str) -> bool:
90
+ """Whether a rate-limit pause holds ``resource`` now."""
91
+ return self._holding(resource) is not None
92
+
93
+ async def wait(self, resource: str) -> None:
94
+ """Return once no pause holds ``resource``.
95
+
96
+ The pauses are checked again after each wakeup: another may have
97
+ begun before this waiter ran.
98
+ """
99
+ while (key := self._holding(resource)) is not None:
100
+ await self._event(key).wait()
101
+
102
+ def stop(self, key: str) -> None:
103
+ """Mark ``key``, or every resource for ``ALL``, spent for the run."""
104
+ self._stopped.add(key)
105
+
106
+ def stopped(self, resource: str) -> bool:
107
+ """Whether a terminal rate limit has stopped ``resource``."""
108
+ return resource in self._stopped or ALL in self._stopped
109
+
110
+ def close(self) -> None:
111
+ """Cancel every pause still running, as the transport closes."""
112
+ for task in list(self._pauses):
113
+ task.cancel()
@@ -0,0 +1,60 @@
1
+ # SPDX-License-Identifier: Apache-2.0
2
+ # SPDX-FileCopyrightText: 2026 The Linux Foundation
3
+ """Errors the GitHub client raises (design §4.1 ``client/``)."""
4
+
5
+ from __future__ import annotations
6
+
7
+ from typing import Any
8
+
9
+
10
+ class ClientError(Exception):
11
+ """Base class for every error the GitHub client raises."""
12
+
13
+
14
+ class AuthError(ClientError):
15
+ """GitHub rejected the token (HTTP 401); the run must stop."""
16
+
17
+
18
+ class TransportError(ClientError):
19
+ """A request could not complete within the retry and wait budget."""
20
+
21
+
22
+ class BudgetExhaustedError(ClientError):
23
+ """The budget has no REST request or GraphQL point left for a request.
24
+
25
+ Also raised, unsent, for a resource a rate limit that outlasted a
26
+ request's retries has stopped for the run.
27
+
28
+ Not a failure of the run: a collector that meets it stops cleanly,
29
+ as it would on finding ``rest_exhausted`` or ``graphql_exhausted``
30
+ set (design §6.5).
31
+ """
32
+
33
+
34
+ class ForeignHostError(ClientError):
35
+ """A request named a host other than the configured API host."""
36
+
37
+
38
+ class GraphQLError(ClientError):
39
+ """A GraphQL query failed, by error payload or by HTTP status.
40
+
41
+ ``status`` is the HTTP status when GitHub did not answer ``200``,
42
+ and ``None`` when it answered ``200`` with an ``errors`` payload.
43
+ ``request_wide`` is true when the failure is not the fault of any id
44
+ in the query (a rate limit, or a query GitHub refused to run), so a
45
+ smaller batch cannot avoid it.
46
+ """
47
+
48
+ def __init__(
49
+ self,
50
+ message: str,
51
+ *,
52
+ errors: list[dict[str, Any]] | None = None,
53
+ status: int | None = None,
54
+ request_wide: bool = False,
55
+ ) -> None:
56
+ """Record the message, the ``errors`` payload, the status and its scope."""
57
+ super().__init__(message)
58
+ self.errors = errors or []
59
+ self.status = status
60
+ self.request_wide = request_wide
@@ -0,0 +1,281 @@
1
+ # SPDX-License-Identifier: Apache-2.0
2
+ # SPDX-FileCopyrightText: 2026 The Linux Foundation
3
+ """GraphQL queries and halving batches over a ``Transport``."""
4
+
5
+ from __future__ import annotations
6
+
7
+ import logging
8
+ import time
9
+ from collections.abc import Awaitable, Callable, Sequence
10
+ from dataclasses import dataclass, field
11
+ from typing import Any, Generic, TypeVar
12
+
13
+ from .errors import BudgetExhaustedError, GraphQLError
14
+ from .policy import (
15
+ errors_name_secondary,
16
+ errors_rate_limited,
17
+ rate_limited,
18
+ write_operation,
19
+ )
20
+ from .transport import Transport
21
+
22
+ log = logging.getLogger(__name__)
23
+
24
+ T = TypeVar("T")
25
+ K = TypeVar("K")
26
+
27
+ # How GitHub answers a GraphQL query that ran out of time.
28
+ TIMEOUT_STATUSES = frozenset({502, 504})
29
+
30
+ # Chunks a batch lets time out before it stops: each one may have spent
31
+ # the transport's retries and wait, so persistent 502s would otherwise
32
+ # outlast the job. Enough for one id's descent from a chunk of 100.
33
+ MAX_TIMEOUTS = 10
34
+
35
+ # Seconds a batch lets its timed-out chunks take, their attempts and
36
+ # backoff together, before it stops.
37
+ MAX_TIMEOUT_SECONDS = 300.0
38
+
39
+ # What GitHub says, in an HTTP 200 error payload, of a query that may
40
+ # have run out of time.
41
+ TIMEOUT_DIAGNOSTIC = "the result of a timeout"
42
+
43
+ # Error types a smaller query can avoid, though GitHub refuses the query.
44
+ SIZE_ERROR_TYPES = frozenset({"MAX_NODE_LIMIT_EXCEEDED", "RESOURCE_LIMITS_EXCEEDED"})
45
+
46
+
47
+ def _request_wide(payload: dict[str, Any], errors: list[Any]) -> bool:
48
+ """Whether an error payload fails the whole query, whatever ids it names.
49
+
50
+ A rate-limit error, primary or secondary, is. So is a payload
51
+ without ``data``, which GitHub sends for a query it refused to run
52
+ (a syntax or validation error), unless the refusal is about the
53
+ query's size or its time.
54
+ """
55
+ if errors_rate_limited(errors):
56
+ return True
57
+ types = {error.get("type") for error in errors if isinstance(error, dict)}
58
+ return (
59
+ "data" not in payload
60
+ and not types & SIZE_ERROR_TYPES
61
+ and not _names_timeout(errors)
62
+ )
63
+
64
+
65
+ def _names_timeout(errors: list[Any]) -> bool:
66
+ """Whether an error payload carries GitHub's timeout diagnostic."""
67
+ return any(
68
+ isinstance(error, dict)
69
+ and isinstance(error.get("message"), str)
70
+ and TIMEOUT_DIAGNOSTIC in error["message"].lower()
71
+ for error in errors
72
+ )
73
+
74
+
75
+ def _timed_out(exc: GraphQLError) -> bool:
76
+ """Whether ``exc`` is a query that ran out of time.
77
+
78
+ GitHub reports one as a ``502`` or ``504``, or as an HTTP ``200``
79
+ whose error payload says it may be the result of a timeout.
80
+ """
81
+ if exc.status is not None:
82
+ return exc.status in TIMEOUT_STATUSES
83
+ return _names_timeout(exc.errors)
84
+
85
+
86
+ def _record_rate(transport: Transport, data: Any) -> int | None:
87
+ """Record ``data``'s ``rateLimit`` in the stats; return its cost, if any."""
88
+ rate = data.get("rateLimit") if isinstance(data, dict) else None
89
+ if not isinstance(rate, dict):
90
+ return None
91
+ remaining = rate.get("remaining")
92
+ if isinstance(remaining, int):
93
+ transport.stats.graphql_remaining = remaining
94
+ cost = rate.get("cost")
95
+ if not isinstance(cost, int):
96
+ return None
97
+ transport.stats.graphql_cost += cost
98
+ return cost
99
+
100
+
101
+ async def graphql(
102
+ transport: Transport,
103
+ query: str,
104
+ variables: dict[str, Any] | None = None,
105
+ *,
106
+ cost_estimate: int | None = None,
107
+ ) -> dict[str, Any]:
108
+ """Post the read-only ``query`` and return its ``data``.
109
+
110
+ A document defining a ``mutation`` or ``subscription`` raises
111
+ ``ValueError`` before anything is sent: the client only reads. The
112
+ check guards against misuse and is not a security boundary.
113
+
114
+ GitHub answers a failed query with HTTP ``200`` and an ``errors``
115
+ payload; that raises ``GraphQLError``, marked ``request_wide`` for a
116
+ rate limit or a query GitHub refused to run, as does any status
117
+ other than ``200``, a redirect included, since GitHub does not
118
+ redirect its GraphQL endpoint. The transport retries a ``5xx``, a
119
+ ``429`` and a rate-limit ``403`` like any other request; a ``502`` or
120
+ ``504`` that outlasts the retries raises, so ``batched`` can split
121
+ the query.
122
+
123
+ With a budget, ``cost_estimate`` is required: a bound on the points
124
+ the query may cost, which GitHub does not report until it has run.
125
+ It is taken from the budget once, before the query is sent, and
126
+ ``BudgetExhaustedError`` is raised when it is not left, or given back
127
+ when the query fails before any attempt left the client; the query is
128
+ then charged the cost it reported in ``rateLimit { cost remaining }``,
129
+ even on an error, or the estimate when it reported none.
130
+
131
+ A rate limit that outlasts the transport's retries (a ``429``, or a
132
+ ``403`` with ``Retry-After``, ``x-ratelimit-remaining: 0`` or a body
133
+ naming a secondary rate limit) stops its resource for the run. So
134
+ does an HTTP ``200`` payload with a primary rate-limit error
135
+ (``RATE_LIMITED``, or ``RATE_LIMIT`` with code ``graphql_rate_limit``),
136
+ which stops GraphQL, or with an error whose message names a secondary rate
137
+ limit, which stops every resource; later requests on a stopped
138
+ resource raise ``BudgetExhaustedError`` unsent. Budgeted, the first
139
+ such response also stops the GraphQL budget and raises
140
+ ``BudgetExhaustedError``, so the collector stops cleanly; unbudgeted,
141
+ it raises a request-wide ``GraphQLError``. Any other ``403`` stays a
142
+ permission error.
143
+ """
144
+ operation = write_operation(query)
145
+ if operation is not None:
146
+ raise ValueError(f"the client is read-only; refusing a GraphQL {operation}")
147
+ budget = transport.budget
148
+ estimate = 0
149
+ if budget is not None:
150
+ if cost_estimate is None:
151
+ raise ValueError("a budgeted GraphQL query needs a cost estimate")
152
+ estimate = max(cost_estimate, 1)
153
+ response = await transport._post_graphql(
154
+ {"query": query, "variables": variables or {}}, estimate
155
+ )
156
+ cost: int | None = None
157
+ try:
158
+ if response.status_code != 200:
159
+ limited = rate_limited(response)
160
+ failure = GraphQLError(
161
+ f"GraphQL HTTP {response.status_code}",
162
+ status=response.status_code,
163
+ request_wide=limited,
164
+ )
165
+ if limited and budget is not None:
166
+ budget.exhaust_graphql()
167
+ raise BudgetExhaustedError(
168
+ "GitHub rate-limited a GraphQL query"
169
+ ) from failure
170
+ raise failure
171
+ payload = response.json()
172
+ data = payload.get("data") or {}
173
+ cost = _record_rate(transport, data)
174
+ finally:
175
+ if budget is not None:
176
+ budget.settle_graphql(estimate, cost)
177
+ errors = payload.get("errors")
178
+ if errors:
179
+ first = (
180
+ errors[0].get("message", "unknown error")
181
+ if isinstance(errors[0], dict)
182
+ else errors[0]
183
+ )
184
+ failure = GraphQLError(
185
+ f"GraphQL query failed: {first}",
186
+ errors=list(errors),
187
+ request_wide=_request_wide(payload, errors),
188
+ )
189
+ if errors_rate_limited(errors):
190
+ transport.stop(errors_name_secondary(errors))
191
+ if budget is not None:
192
+ budget.exhaust_graphql()
193
+ raise BudgetExhaustedError(
194
+ "GitHub rate-limited a GraphQL query"
195
+ ) from failure
196
+ raise failure
197
+ return data
198
+
199
+
200
+ @dataclass
201
+ class Batched(Generic[T, K]):
202
+ """What ``batched`` fetched: one result per chunk, and the ids it did not.
203
+
204
+ ``failed`` holds the ids that failed alone; ``remaining`` the ids
205
+ never fetched because the budget ran out or too many chunks timed
206
+ out, in their original order.
207
+ """
208
+
209
+ results: list[T] = field(default_factory=list)
210
+ failed: list[K] = field(default_factory=list)
211
+ remaining: list[K] = field(default_factory=list)
212
+
213
+
214
+ async def batched(
215
+ ids: Sequence[K],
216
+ size: int,
217
+ fetch: Callable[[list[K]], Awaitable[T]],
218
+ describe: Callable[[list[K]], str],
219
+ max_timeouts: int = MAX_TIMEOUTS,
220
+ max_timeout_seconds: float = MAX_TIMEOUT_SECONDS,
221
+ clock: Callable[[], float] = time.monotonic,
222
+ ) -> Batched[T, K]:
223
+ """Call ``fetch`` on chunks of ``ids`` of at most ``size``, halving on failure.
224
+
225
+ A chunk that fails with an error payload or a ``502``/``504`` is
226
+ split in two and each half retried, down to one id; an id that fails
227
+ alone goes in ``failed`` and the rest carry on. A request-wide error
228
+ (a rate limit, a query GitHub refused) propagates at once, since
229
+ splitting cannot avoid it and would multiply the failing requests;
230
+ so does any other error. ``describe(chunk)`` names a chunk in the log.
231
+
232
+ When ``fetch`` raises ``BudgetExhaustedError``, or the chunks that
233
+ timed out, by a ``502``/``504`` or an error payload carrying GitHub's
234
+ timeout diagnostic, reach ``max_timeouts`` or have taken
235
+ ``max_timeout_seconds`` by ``clock``, requests and retry waits
236
+ included, batching stops: the results so far return, with the chunk
237
+ that met it and every chunk not yet fetched in ``remaining``, so a
238
+ collector keeps its work and persistent timeouts cannot outlast the
239
+ run. Chunks that succeed, however slow, are not bounded.
240
+ """
241
+ if size < 1:
242
+ raise ValueError(f"batch size must be at least 1, not {size}")
243
+ out: Batched[T, K] = Batched()
244
+ pending = [list(ids[start : start + size]) for start in range(0, len(ids), size)]
245
+ pending.reverse()
246
+ timeouts = 0
247
+ timed_out = 0.0
248
+ while pending:
249
+ chunk = pending.pop()
250
+ started = clock()
251
+ try:
252
+ out.results.append(await fetch(chunk))
253
+ except BudgetExhaustedError:
254
+ log.info("budget exhausted at %s", describe(chunk))
255
+ out.remaining = chunk + [i for rest in reversed(pending) for i in rest]
256
+ return out
257
+ except GraphQLError as exc:
258
+ if exc.request_wide or (
259
+ exc.status is not None and exc.status not in TIMEOUT_STATUSES
260
+ ):
261
+ raise
262
+ if _timed_out(exc):
263
+ timeouts += 1
264
+ timed_out += clock() - started
265
+ if timeouts >= max_timeouts or timed_out >= max_timeout_seconds:
266
+ log.warning(
267
+ "stopping at %s: %d timeouts", describe(chunk), timeouts
268
+ )
269
+ out.remaining = chunk + [
270
+ i for rest in reversed(pending) for i in rest
271
+ ]
272
+ return out
273
+ if len(chunk) == 1:
274
+ log.warning("giving up on %s: %s", describe(chunk), exc)
275
+ out.failed.append(chunk[0])
276
+ continue
277
+ middle = len(chunk) // 2
278
+ log.info("splitting %s after: %s", describe(chunk), exc)
279
+ pending.append(chunk[middle:])
280
+ pending.append(chunk[:middle])
281
+ return out
@@ -0,0 +1,92 @@
1
+ # SPDX-License-Identifier: Apache-2.0
2
+ # SPDX-FileCopyrightText: 2026 The Linux Foundation
3
+ """REST pagination and conditional requests over a ``Transport``."""
4
+
5
+ from __future__ import annotations
6
+
7
+ from collections.abc import AsyncIterator, Mapping
8
+ from dataclasses import dataclass
9
+ from typing import Any
10
+
11
+ import httpx
12
+
13
+ from .transport import Transport
14
+
15
+
16
+ def _items(body: Any, items_key: str | None) -> list[Any]:
17
+ """The list of items in one page ``body``."""
18
+ if items_key is not None:
19
+ body = body[items_key]
20
+ if not isinstance(body, list):
21
+ raise ValueError("page body is not a list; name its items_key")
22
+ return body
23
+
24
+
25
+ async def get_paged(
26
+ transport: Transport,
27
+ url: str,
28
+ params: Mapping[str, Any] | None = None,
29
+ *,
30
+ items_key: str | None = None,
31
+ ) -> AsyncIterator[tuple[list[Any], httpx.Response]]:
32
+ """Yield ``(items, response)`` for each page, following ``rel="next"``.
33
+
34
+ ``items_key`` names the list in an object body (``workflow_runs``);
35
+ a list body needs none. The caller decides when to stop. A page that
36
+ is not a success raises ``httpx.HTTPStatusError``. The next link
37
+ already carries the query, so ``params`` goes with the first page
38
+ only. A relative link resolves against the page it came from, and
39
+ the transport refuses a link to any other host.
40
+ """
41
+ next_url: str | None = url
42
+ next_params = params
43
+ while next_url is not None:
44
+ response = await transport.request("GET", next_url, params=next_params)
45
+ response.raise_for_status()
46
+ yield _items(response.json(), items_key), response
47
+ link = response.links.get("next")
48
+ target = link.get("url") if link else None
49
+ next_url = str(response.url.join(target)) if target else None
50
+ next_params = None
51
+
52
+
53
+ @dataclass(frozen=True)
54
+ class Conditional:
55
+ """The answer to a conditional request.
56
+
57
+ ``not_modified`` is true for a ``304``, which carries no body and
58
+ keeps the ETag sent; otherwise ``body`` is the decoded JSON and
59
+ ``etag`` the new ETag, ``None`` when GitHub sent none.
60
+ """
61
+
62
+ not_modified: bool
63
+ body: Any
64
+ etag: str | None
65
+ response: httpx.Response
66
+
67
+
68
+ async def get_conditional(
69
+ transport: Transport,
70
+ url: str,
71
+ params: Mapping[str, Any] | None = None,
72
+ etag: str | None = None,
73
+ ) -> Conditional:
74
+ """``GET url`` with ``If-None-Match: etag``.
75
+
76
+ GitHub charges no rate limit for a ``304`` to an authenticated
77
+ request; an anonymous one is charged like any other.
78
+
79
+ A response that is neither ``304`` nor a success raises
80
+ ``httpx.HTTPStatusError``.
81
+ """
82
+ headers = {"If-None-Match": etag} if etag else None
83
+ response = await transport.request("GET", url, params=params, headers=headers)
84
+ if response.status_code == 304:
85
+ return Conditional(not_modified=True, body=None, etag=etag, response=response)
86
+ response.raise_for_status()
87
+ return Conditional(
88
+ not_modified=False,
89
+ body=response.json(),
90
+ etag=response.headers.get("etag"),
91
+ response=response,
92
+ )