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.
- github_statistics/__init__.py +14 -0
- github_statistics/__main__.py +10 -0
- github_statistics/_version.py +24 -0
- github_statistics/cli/__init__.py +9 -0
- github_statistics/cli/app.py +104 -0
- github_statistics/cli/cache.py +159 -0
- github_statistics/cli/collect.py +219 -0
- github_statistics/cli/common.py +128 -0
- github_statistics/cli/config.py +80 -0
- github_statistics/cli/doctor.py +214 -0
- github_statistics/cli/export.py +111 -0
- github_statistics/cli/options.py +175 -0
- github_statistics/cli/render.py +126 -0
- github_statistics/cli/run.py +137 -0
- github_statistics/cli/scope.py +96 -0
- github_statistics/cli/site.py +150 -0
- github_statistics/client/__init__.py +40 -0
- github_statistics/client/accounting.py +99 -0
- github_statistics/client/budget.py +125 -0
- github_statistics/client/cooldown.py +113 -0
- github_statistics/client/errors.py +60 -0
- github_statistics/client/graphql.py +281 -0
- github_statistics/client/paging.py +92 -0
- github_statistics/client/policy.py +243 -0
- github_statistics/client/transport.py +437 -0
- github_statistics/collect/__init__.py +44 -0
- github_statistics/collect/common.py +69 -0
- github_statistics/collect/enrich_items.py +423 -0
- github_statistics/collect/items.py +238 -0
- github_statistics/collect/jobs.py +194 -0
- github_statistics/collect/listed.py +42 -0
- github_statistics/collect/members.py +70 -0
- github_statistics/collect/reader.py +124 -0
- github_statistics/collect/run.py +354 -0
- github_statistics/collect/runs.py +436 -0
- github_statistics/collect/slices.py +55 -0
- github_statistics/collect/steps.py +154 -0
- github_statistics/collect/sweep.py +70 -0
- github_statistics/config/__init__.py +37 -0
- github_statistics/config/loader.py +430 -0
- github_statistics/config/models.py +156 -0
- github_statistics/config/schema.py +245 -0
- github_statistics/export/__init__.py +11 -0
- github_statistics/export/csv.py +93 -0
- github_statistics/export/documents.py +189 -0
- github_statistics/export/json.py +33 -0
- github_statistics/py.typed +2 -0
- github_statistics/render/__init__.py +44 -0
- github_statistics/render/bars3d.py +420 -0
- github_statistics/render/charts.py +214 -0
- github_statistics/render/demo.py +133 -0
- github_statistics/render/images.py +31 -0
- github_statistics/render/layout.py +341 -0
- github_statistics/render/model.py +260 -0
- github_statistics/render/palette.py +41 -0
- github_statistics/scope/__init__.py +17 -0
- github_statistics/scope/apply.py +95 -0
- github_statistics/scope/resolver.py +228 -0
- github_statistics/series/__init__.py +22 -0
- github_statistics/series/actors.py +128 -0
- github_statistics/series/coverage.py +86 -0
- github_statistics/series/daily.py +229 -0
- github_statistics/series/leaderboard.py +221 -0
- github_statistics/series/repositories.py +154 -0
- github_statistics/site/__init__.py +9 -0
- github_statistics/site/assets/site.css +281 -0
- github_statistics/site/build.py +392 -0
- github_statistics/site/templates/base.html.j2 +25 -0
- github_statistics/site/templates/index.html.j2 +30 -0
- github_statistics/site/templates/macros.html.j2 +5 -0
- github_statistics/site/templates/site.js.j2 +66 -0
- github_statistics/site/templates/target.html.j2 +95 -0
- github_statistics/store/__init__.py +40 -0
- github_statistics/store/activity.py +311 -0
- github_statistics/store/aggregates.py +294 -0
- github_statistics/store/base.py +163 -0
- github_statistics/store/codec.py +263 -0
- github_statistics/store/models.py +136 -0
- github_statistics/store/paths.py +36 -0
- github_statistics/store/schema.py +169 -0
- github_statistics/store/sqlite.py +299 -0
- github_statistics-0.1.0.dist-info/METADATA +308 -0
- github_statistics-0.1.0.dist-info/RECORD +86 -0
- github_statistics-0.1.0.dist-info/WHEEL +4 -0
- github_statistics-0.1.0.dist-info/entry_points.txt +2 -0
- github_statistics-0.1.0.dist-info/licenses/LICENSE +201 -0
|
@@ -0,0 +1,436 @@
|
|
|
1
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
2
|
+
# SPDX-FileCopyrightText: 2026 The Linux Foundation
|
|
3
|
+
"""Collect workflow runs from the Actions listing (design §6.4).
|
|
4
|
+
|
|
5
|
+
The ``runs`` sync state holds the newest ``created_at`` stored as
|
|
6
|
+
``watermark``, the listing's first-page ETag, and ``oldest``: every run
|
|
7
|
+
from ``oldest`` to the watermark is stored, unless the backfill reached
|
|
8
|
+
the listing horizon. A day is covered once every run on it is read.
|
|
9
|
+
The ``runs_gap`` state's ``watermark`` holds the end of the newest
|
|
10
|
+
range read only up to the listing cap; no later read covers its day.
|
|
11
|
+
Its ``oldest`` holds the start of the oldest such range; the backfill
|
|
12
|
+
covers no day from that one up.
|
|
13
|
+
The ``runs_hole`` state holds a range an incremental read left unread
|
|
14
|
+
below the runs it stored, from ``oldest`` to ``watermark``; the next
|
|
15
|
+
read fills it first, and covers its days only once it is filled; the
|
|
16
|
+
state is cleared once they are covered.
|
|
17
|
+
The ``runs`` state's ``swept_to`` holds when a re-run sweep last ended.
|
|
18
|
+
"""
|
|
19
|
+
|
|
20
|
+
from __future__ import annotations
|
|
21
|
+
|
|
22
|
+
import dataclasses
|
|
23
|
+
import logging
|
|
24
|
+
from collections.abc import Awaitable, Callable
|
|
25
|
+
from dataclasses import dataclass
|
|
26
|
+
from datetime import UTC, date, datetime, timedelta
|
|
27
|
+
|
|
28
|
+
import httpx
|
|
29
|
+
|
|
30
|
+
from github_statistics.client import (
|
|
31
|
+
BudgetExhaustedError,
|
|
32
|
+
Transport,
|
|
33
|
+
get_conditional,
|
|
34
|
+
get_paged,
|
|
35
|
+
)
|
|
36
|
+
from github_statistics.client.policy import rate_limited
|
|
37
|
+
from github_statistics.scope import ResolvedScope
|
|
38
|
+
from github_statistics.store import Run, Store, SyncState
|
|
39
|
+
|
|
40
|
+
from .common import run_concurrently, scope_keys, unreadable_status
|
|
41
|
+
from .listed import listed_run, reaches
|
|
42
|
+
from .reader import PER_PAGE, RUNS_KEY, SliceReader
|
|
43
|
+
from .slices import DAY, SECOND, first_full_day, midnight, slice_below, timestamp
|
|
44
|
+
|
|
45
|
+
log = logging.getLogger(__name__)
|
|
46
|
+
|
|
47
|
+
# The sync state and coverage metric of the listing.
|
|
48
|
+
RUNS_METRIC = "runs"
|
|
49
|
+
HOLE_METRIC = "runs_hole"
|
|
50
|
+
PENDING_LIMIT = 50
|
|
51
|
+
SLICE_DAYS = 7
|
|
52
|
+
# GitHub allows a re-run for 30 days after the first run.
|
|
53
|
+
RERUN_DAYS = timedelta(days=30)
|
|
54
|
+
SWEEP_EVERY = timedelta(days=7)
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
@dataclass(frozen=True)
|
|
58
|
+
class RunSyncResult:
|
|
59
|
+
"""What one repository's run sync did.
|
|
60
|
+
|
|
61
|
+
``current``: the incremental read finished. ``reached``: history
|
|
62
|
+
reaches the window start or the listing horizon. ``unreadable``: the
|
|
63
|
+
HTTP status that made the repository unreadable, else ``None``.
|
|
64
|
+
``stalled``: a spent budget stopped a read inside the second it
|
|
65
|
+
started from (`SliceReader.read`).
|
|
66
|
+
"""
|
|
67
|
+
|
|
68
|
+
repo: str
|
|
69
|
+
runs: int
|
|
70
|
+
pages: int
|
|
71
|
+
current: bool
|
|
72
|
+
reached: bool
|
|
73
|
+
unreadable: int | None = None
|
|
74
|
+
stalled: bool = False
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
class _RunSync(SliceReader):
|
|
78
|
+
"""One repository's run sync, in the phases `sync_all_runs` orders."""
|
|
79
|
+
|
|
80
|
+
def __init__(
|
|
81
|
+
self,
|
|
82
|
+
transport: Transport,
|
|
83
|
+
store: Store,
|
|
84
|
+
key: str,
|
|
85
|
+
*,
|
|
86
|
+
window_start: date,
|
|
87
|
+
now: datetime,
|
|
88
|
+
) -> None:
|
|
89
|
+
"""Prepare the sync of ``key`` (``owner/name``) from its stored state."""
|
|
90
|
+
super().__init__(transport, store, key)
|
|
91
|
+
self.window_start = window_start
|
|
92
|
+
self.target = midnight(window_start)
|
|
93
|
+
self.now = now
|
|
94
|
+
self.yesterday = now.astimezone(UTC).date() - DAY
|
|
95
|
+
self.state = store.sync_state(key, RUNS_METRIC) or SyncState(key, RUNS_METRIC)
|
|
96
|
+
self.hole = store.sync_state(key, HOLE_METRIC)
|
|
97
|
+
self.current = False
|
|
98
|
+
self.unreadable: int | None = None
|
|
99
|
+
|
|
100
|
+
def result(self) -> RunSyncResult:
|
|
101
|
+
"""What the sync has done so far."""
|
|
102
|
+
oldest = self.state.oldest
|
|
103
|
+
reached = oldest is not None and oldest <= self.target
|
|
104
|
+
return RunSyncResult(
|
|
105
|
+
self.key,
|
|
106
|
+
self.runs,
|
|
107
|
+
self.pages,
|
|
108
|
+
self.current,
|
|
109
|
+
reached,
|
|
110
|
+
self.unreadable,
|
|
111
|
+
self.stalled,
|
|
112
|
+
)
|
|
113
|
+
|
|
114
|
+
async def guarded(self, phase: Callable[[], Awaitable[None]]) -> bool:
|
|
115
|
+
"""Run ``phase``; whether it finished.
|
|
116
|
+
|
|
117
|
+
A spent budget or rate limit stops it cleanly; an unreadable
|
|
118
|
+
status (`unreadable_status`) marks the repository unreadable,
|
|
119
|
+
keeping what was read.
|
|
120
|
+
"""
|
|
121
|
+
try:
|
|
122
|
+
await phase()
|
|
123
|
+
except BudgetExhaustedError as exc:
|
|
124
|
+
log.info("stopped syncing runs of %s: %s", self.key, exc)
|
|
125
|
+
return False
|
|
126
|
+
except httpx.HTTPStatusError as exc:
|
|
127
|
+
status = unreadable_status(exc)
|
|
128
|
+
if status is None:
|
|
129
|
+
log.info("stopped syncing runs of %s: rate limited", self.key)
|
|
130
|
+
else:
|
|
131
|
+
log.warning("cannot read runs of %s: HTTP %s", self.key, status)
|
|
132
|
+
self.unreadable = status
|
|
133
|
+
return False
|
|
134
|
+
return True
|
|
135
|
+
|
|
136
|
+
async def recent(self) -> None:
|
|
137
|
+
"""The incremental read, then the pending re-reads.
|
|
138
|
+
|
|
139
|
+
The read's coverage is added once the re-reads end, unless one
|
|
140
|
+
finds the repository unreadable: the sync state and hole then go
|
|
141
|
+
back to what they were, so the next sync reads those runs again
|
|
142
|
+
and covers their days.
|
|
143
|
+
"""
|
|
144
|
+
pending = {run.id for run in self.store.pending_runs(self.key)}
|
|
145
|
+
before, hole = self.state, self.hole
|
|
146
|
+
span = await self._incremental()
|
|
147
|
+
self.current = True
|
|
148
|
+
unreadable = False
|
|
149
|
+
try:
|
|
150
|
+
await self._reread(pending)
|
|
151
|
+
except httpx.HTTPStatusError as exc:
|
|
152
|
+
unreadable = not rate_limited(exc.response)
|
|
153
|
+
raise
|
|
154
|
+
finally:
|
|
155
|
+
if unreadable:
|
|
156
|
+
self._save(before)
|
|
157
|
+
self._hole(hole or SyncState(self.key, HOLE_METRIC))
|
|
158
|
+
elif span is not None:
|
|
159
|
+
self._cover(*span)
|
|
160
|
+
if self.hole is not None and self.hole.oldest is not None:
|
|
161
|
+
self._hole(SyncState(self.key, HOLE_METRIC))
|
|
162
|
+
|
|
163
|
+
async def backfill(self) -> None:
|
|
164
|
+
"""Read week slices below ``oldest``, newest first, to the window start.
|
|
165
|
+
|
|
166
|
+
An empty slice is followed by one probe for the newest run listed
|
|
167
|
+
below it (`_older`). The days between are empty: they gain
|
|
168
|
+
coverage, and the backfill goes on from the slice ending on that
|
|
169
|
+
run's day. With nothing older listed, the backfill ends at the
|
|
170
|
+
listing horizon, covering none of the slice's days but that of an
|
|
171
|
+
intra-day ``oldest`` it completes. A split slice checkpoints after
|
|
172
|
+
each part (`_checkpoint`).
|
|
173
|
+
"""
|
|
174
|
+
cursor = self.state.oldest
|
|
175
|
+
while cursor is not None and cursor > self.target:
|
|
176
|
+
low = slice_below(cursor, self.target, SLICE_DAYS)
|
|
177
|
+
read, complete = await self.read(low, cursor - SECOND, self._checkpoint)
|
|
178
|
+
if read == 0:
|
|
179
|
+
older = await self._older(low)
|
|
180
|
+
if older is None:
|
|
181
|
+
log.info("no runs of %s listed before %s", self.key, low)
|
|
182
|
+
self._cover_read(cursor.astimezone(UTC).date())
|
|
183
|
+
self._save(dataclasses.replace(self.state, oldest=self.target))
|
|
184
|
+
return
|
|
185
|
+
after = midnight(older.astimezone(UTC).date()) + DAY
|
|
186
|
+
low = max(self.target, min(low, after))
|
|
187
|
+
self._checkpoint(low, complete)
|
|
188
|
+
cursor = low
|
|
189
|
+
|
|
190
|
+
async def sweep(self) -> None:
|
|
191
|
+
"""Re-read the runs a re-run may have changed (`sweep_runs`).
|
|
192
|
+
|
|
193
|
+
Records no checkpoint, so ``oldest``, the watermark and coverage
|
|
194
|
+
stay as they were; ``swept_to`` moves to now once the read ends.
|
|
195
|
+
An hour over the listing cap does not hold it: no later read can
|
|
196
|
+
list more of that hour, and ``runs_gap`` records it already.
|
|
197
|
+
"""
|
|
198
|
+
since = self.state.swept_to or self.now - SWEEP_EVERY
|
|
199
|
+
await self.read(since - RERUN_DAYS, self.now, lambda _low, _done: None)
|
|
200
|
+
self._save(dataclasses.replace(self.state, swept_to=self.now))
|
|
201
|
+
|
|
202
|
+
async def _older(self, below: datetime) -> datetime | None:
|
|
203
|
+
"""When the newest run listed as created before ``below`` was, if any."""
|
|
204
|
+
params = {"per_page": 1, "created": f"<{timestamp(below)}"}
|
|
205
|
+
response = await self.transport.request("GET", self.path, params=params)
|
|
206
|
+
self.pages += 1
|
|
207
|
+
response.raise_for_status()
|
|
208
|
+
listed = response.json()[RUNS_KEY]
|
|
209
|
+
if not listed:
|
|
210
|
+
return None
|
|
211
|
+
return datetime.fromisoformat(listed[0]["created_at"])
|
|
212
|
+
|
|
213
|
+
def _checkpoint(self, low: datetime, complete: bool) -> None:
|
|
214
|
+
"""Record that every run from ``low`` up to ``oldest`` is read.
|
|
215
|
+
|
|
216
|
+
If ``complete``, cover the whole days read, short of the day of a
|
|
217
|
+
part read only up to the cap (`_cover_read`).
|
|
218
|
+
"""
|
|
219
|
+
top = self.state.oldest
|
|
220
|
+
if top is None or low >= top:
|
|
221
|
+
return
|
|
222
|
+
if complete:
|
|
223
|
+
self._cover_read(first_full_day(low))
|
|
224
|
+
self._save(dataclasses.replace(self.state, oldest=low))
|
|
225
|
+
|
|
226
|
+
def _cover_read(self, start: date) -> None:
|
|
227
|
+
"""Cover the days from ``start`` to the last one ending above ``oldest``.
|
|
228
|
+
|
|
229
|
+
Every run from ``oldest`` up is read, so a caller that has read
|
|
230
|
+
all of ``start``'s day and the days after it below ``oldest``
|
|
231
|
+
completes them. Stops short of the day of the oldest part read
|
|
232
|
+
only up to the cap (the ``runs_gap`` state).
|
|
233
|
+
"""
|
|
234
|
+
top = self.state.oldest
|
|
235
|
+
if top is None:
|
|
236
|
+
return
|
|
237
|
+
end = first_full_day(top) - DAY
|
|
238
|
+
if self.gap_low is not None:
|
|
239
|
+
end = min(end, self.gap_low.astimezone(UTC).date() - DAY)
|
|
240
|
+
self._cover(start, end)
|
|
241
|
+
|
|
242
|
+
async def _incremental(self) -> tuple[date, date] | None:
|
|
243
|
+
"""Read the listing newest first down to the watermark; days to cover.
|
|
244
|
+
|
|
245
|
+
A hole an earlier read left is filled first (`_fill`). Where the
|
|
246
|
+
listing stops at its cap, or a spent budget stops the paging,
|
|
247
|
+
above the watermark, the runs read are stored and the rest
|
|
248
|
+
becomes a hole, which date slices fill; on a first sync, the
|
|
249
|
+
backfill reads it instead.
|
|
250
|
+
"""
|
|
251
|
+
start = await self._fill()
|
|
252
|
+
state = self.state
|
|
253
|
+
since = state.watermark or state.oldest or self.target
|
|
254
|
+
start = since if start is None else min(start, since)
|
|
255
|
+
answer = await get_conditional(
|
|
256
|
+
self.transport, self.path, {"per_page": PER_PAGE}, state.etag
|
|
257
|
+
)
|
|
258
|
+
self.pages += 1
|
|
259
|
+
if answer.not_modified:
|
|
260
|
+
self._store(dataclasses.replace(state, last_sync_at=self.now), [])
|
|
261
|
+
return self._span(start)
|
|
262
|
+
total = int(answer.body["total_count"])
|
|
263
|
+
listed = [listed_run(self.key, data) for data in answer.body[RUNS_KEY]]
|
|
264
|
+
stopped: BudgetExhaustedError | None = None
|
|
265
|
+
link = answer.response.links.get("next")
|
|
266
|
+
if link and link.get("url") and not reaches(listed, since):
|
|
267
|
+
url = str(answer.response.url.join(link["url"]))
|
|
268
|
+
try:
|
|
269
|
+
async for page, _response in get_paged(
|
|
270
|
+
self.transport, url, items_key=RUNS_KEY
|
|
271
|
+
):
|
|
272
|
+
self.pages += 1
|
|
273
|
+
batch = [listed_run(self.key, data) for data in page]
|
|
274
|
+
listed.extend(batch)
|
|
275
|
+
if reaches(batch, since):
|
|
276
|
+
break
|
|
277
|
+
except BudgetExhaustedError as exc:
|
|
278
|
+
log.info("budget spent paging runs of %s; next sync resumes", self.key)
|
|
279
|
+
stopped = exc
|
|
280
|
+
oldest = state.oldest or self.target
|
|
281
|
+
hole = None
|
|
282
|
+
if listed and not reaches(listed, since) and (stopped or len(listed) < total):
|
|
283
|
+
bottom = min(run.created_at for run in listed)
|
|
284
|
+
if state.oldest is None:
|
|
285
|
+
oldest = bottom + SECOND
|
|
286
|
+
else:
|
|
287
|
+
hole = SyncState(self.key, HOLE_METRIC, watermark=bottom, oldest=start)
|
|
288
|
+
self._hole(hole)
|
|
289
|
+
newest = [run.created_at for run in listed]
|
|
290
|
+
if state.watermark is not None:
|
|
291
|
+
newest.append(state.watermark)
|
|
292
|
+
new = dataclasses.replace(
|
|
293
|
+
state,
|
|
294
|
+
watermark=max(newest, default=None),
|
|
295
|
+
etag=answer.etag,
|
|
296
|
+
oldest=oldest,
|
|
297
|
+
last_sync_at=self.now,
|
|
298
|
+
)
|
|
299
|
+
self._store(new, listed)
|
|
300
|
+
if hole is not None:
|
|
301
|
+
if stopped is not None:
|
|
302
|
+
raise stopped
|
|
303
|
+
await self._fill()
|
|
304
|
+
return self._span(start)
|
|
305
|
+
|
|
306
|
+
async def _fill(self) -> datetime | None:
|
|
307
|
+
"""Read the stored hole, newest first; where its days start, if any.
|
|
308
|
+
|
|
309
|
+
Each page and part read lowers the hole's top
|
|
310
|
+
(`_fill_checkpoint`), so a spent budget resumes below it. A filled
|
|
311
|
+
hole keeps its start, with its top below it, until `recent`
|
|
312
|
+
covers its days.
|
|
313
|
+
"""
|
|
314
|
+
hole = self.hole
|
|
315
|
+
if hole is None or hole.oldest is None or hole.watermark is None:
|
|
316
|
+
return None
|
|
317
|
+
if hole.watermark >= hole.oldest:
|
|
318
|
+
await self.read(hole.oldest, hole.watermark, self._fill_checkpoint)
|
|
319
|
+
self._hole(dataclasses.replace(hole, watermark=hole.oldest - SECOND))
|
|
320
|
+
return hole.oldest
|
|
321
|
+
|
|
322
|
+
def _fill_checkpoint(self, low: datetime, _complete: bool) -> None:
|
|
323
|
+
"""Record that the hole's runs from ``low`` up are read."""
|
|
324
|
+
hole = self.hole
|
|
325
|
+
if hole is not None and hole.watermark is not None:
|
|
326
|
+
if low - SECOND < hole.watermark:
|
|
327
|
+
self._hole(dataclasses.replace(hole, watermark=low - SECOND))
|
|
328
|
+
|
|
329
|
+
def _store(self, state: SyncState, listed: list[Run]) -> None:
|
|
330
|
+
"""Store the runs an incremental read listed, with its sync state."""
|
|
331
|
+
self.store.store_run_page(listed, state)
|
|
332
|
+
self.state = state
|
|
333
|
+
self.runs += len(listed)
|
|
334
|
+
|
|
335
|
+
def _span(self, since: datetime) -> tuple[date, date] | None:
|
|
336
|
+
"""The days a finished incremental read covers.
|
|
337
|
+
|
|
338
|
+
They run from that of ``since`` to yesterday, after the day of
|
|
339
|
+
the newest range read only up to the cap (the ``runs_gap`` state).
|
|
340
|
+
"""
|
|
341
|
+
state = self.state
|
|
342
|
+
if state.oldest is None:
|
|
343
|
+
return None
|
|
344
|
+
start = max(since.astimezone(UTC).date(), first_full_day(state.oldest))
|
|
345
|
+
if self.gap is not None:
|
|
346
|
+
start = max(start, self.gap.astimezone(UTC).date() + DAY)
|
|
347
|
+
return start, self.yesterday
|
|
348
|
+
|
|
349
|
+
async def _reread(self, pending: set[int]) -> None:
|
|
350
|
+
"""Re-read by id, oldest first, up to `PENDING_LIMIT` of ``pending``."""
|
|
351
|
+
due = [run for run in self.store.pending_runs(self.key) if run.id in pending]
|
|
352
|
+
for run in due[:PENDING_LIMIT]:
|
|
353
|
+
response = await self.transport.request("GET", f"{self.path}/{run.id}")
|
|
354
|
+
self.pages += 1
|
|
355
|
+
response.raise_for_status()
|
|
356
|
+
self.store.upsert_runs([listed_run(self.key, response.json())])
|
|
357
|
+
self.runs += 1
|
|
358
|
+
|
|
359
|
+
def _cover(self, start: date, end: date) -> None:
|
|
360
|
+
"""Cover ``start`` to ``end``, clipped to the window and to yesterday."""
|
|
361
|
+
start = max(start, self.window_start)
|
|
362
|
+
end = min(end, self.yesterday)
|
|
363
|
+
if start <= end:
|
|
364
|
+
self.store.add_coverage(self.key, RUNS_METRIC, start, end)
|
|
365
|
+
|
|
366
|
+
def _hole(self, state: SyncState) -> None:
|
|
367
|
+
"""Store ``state`` as the hole the incremental read left."""
|
|
368
|
+
self.store.set_sync_state(state)
|
|
369
|
+
self.hole = state
|
|
370
|
+
|
|
371
|
+
def _save(self, state: SyncState) -> None:
|
|
372
|
+
"""Store ``state`` as this repository's run sync state."""
|
|
373
|
+
self.store.set_sync_state(state)
|
|
374
|
+
self.state = state
|
|
375
|
+
|
|
376
|
+
|
|
377
|
+
async def sync_runs(
|
|
378
|
+
transport: Transport,
|
|
379
|
+
store: Store,
|
|
380
|
+
owner: str,
|
|
381
|
+
repo: str,
|
|
382
|
+
*,
|
|
383
|
+
window_start: date,
|
|
384
|
+
now: datetime,
|
|
385
|
+
) -> RunSyncResult:
|
|
386
|
+
"""Sync the workflow runs of ``owner/repo`` into ``store``.
|
|
387
|
+
|
|
388
|
+
The incremental read, up to `PENDING_LIMIT` re-reads of runs still
|
|
389
|
+
in progress, then the backfill to the window start or the listing
|
|
390
|
+
horizon. The budget is the transport's (design §6.5); a spent one
|
|
391
|
+
stops cleanly, keeping what was read. An unreadable repository
|
|
392
|
+
changes no coverage; one with Actions disabled covers the window.
|
|
393
|
+
"""
|
|
394
|
+
sync = _RunSync(
|
|
395
|
+
transport, store, f"{owner}/{repo}", window_start=window_start, now=now
|
|
396
|
+
)
|
|
397
|
+
if await sync.guarded(sync.recent):
|
|
398
|
+
await sync.guarded(sync.backfill)
|
|
399
|
+
return sync.result()
|
|
400
|
+
|
|
401
|
+
|
|
402
|
+
async def sync_all_runs(
|
|
403
|
+
transport: Transport,
|
|
404
|
+
store: Store,
|
|
405
|
+
scope: ResolvedScope,
|
|
406
|
+
*,
|
|
407
|
+
window_start: date,
|
|
408
|
+
now: datetime,
|
|
409
|
+
) -> dict[str, RunSyncResult]:
|
|
410
|
+
"""Sync the runs of every repository in ``scope``; results by ``owner/name``.
|
|
411
|
+
|
|
412
|
+
Every incremental read finishes before any backfill starts, so the
|
|
413
|
+
newest days stay current (design §6.5); a repository the first round
|
|
414
|
+
did not finish is not backfilled. A stopping error propagates as
|
|
415
|
+
itself, ``AuthError`` first, and cancels the others.
|
|
416
|
+
"""
|
|
417
|
+
syncs = [
|
|
418
|
+
_RunSync(transport, store, key, window_start=window_start, now=now)
|
|
419
|
+
for key in scope_keys(store, scope, now)
|
|
420
|
+
]
|
|
421
|
+
finished = await run_concurrently(sync.guarded(sync.recent) for sync in syncs)
|
|
422
|
+
await run_concurrently(
|
|
423
|
+
sync.guarded(sync.backfill)
|
|
424
|
+
for sync, done in zip(syncs, finished, strict=True)
|
|
425
|
+
if done
|
|
426
|
+
)
|
|
427
|
+
return {sync.key: sync.result() for sync in syncs}
|
|
428
|
+
|
|
429
|
+
|
|
430
|
+
def runs_horizon(store: Store, owner: str) -> date | None:
|
|
431
|
+
"""The listing horizon of ``owner``: the day of the oldest run held.
|
|
432
|
+
|
|
433
|
+
GitHub lists runs back about 354 days (measured 2026-11-16); days
|
|
434
|
+
before the horizon chart as no data. ``None`` when no run is held.
|
|
435
|
+
"""
|
|
436
|
+
return store.earliest_run_day(owner)
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
2
|
+
# SPDX-FileCopyrightText: 2026 The Linux Foundation
|
|
3
|
+
"""Date ranges for listings read in ``created=A..B`` slices (design §6.4)."""
|
|
4
|
+
|
|
5
|
+
from __future__ import annotations
|
|
6
|
+
|
|
7
|
+
from datetime import UTC, date, datetime, time, timedelta
|
|
8
|
+
|
|
9
|
+
SECOND = timedelta(seconds=1)
|
|
10
|
+
HOUR = timedelta(hours=1)
|
|
11
|
+
DAY = timedelta(days=1)
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def midnight(day: date) -> datetime:
|
|
15
|
+
"""00:00 UTC on ``day``."""
|
|
16
|
+
return datetime.combine(day, time(), tzinfo=UTC)
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def first_full_day(at: datetime) -> date:
|
|
20
|
+
"""The first day that starts at or after ``at``."""
|
|
21
|
+
day = at.astimezone(UTC).date()
|
|
22
|
+
return day if midnight(day) == at else day + DAY
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def timestamp(at: datetime) -> str:
|
|
26
|
+
"""``at`` as a GitHub search timestamp."""
|
|
27
|
+
return at.astimezone(UTC).strftime("%Y-%m-%dT%H:%M:%SZ")
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def slice_below(cursor: datetime, floor: datetime, days: int) -> datetime:
|
|
31
|
+
"""The start of the ``days``-day slice ending just before ``cursor``.
|
|
32
|
+
|
|
33
|
+
The slice starts at midnight, and no earlier than ``floor``.
|
|
34
|
+
"""
|
|
35
|
+
day = (cursor - SECOND).date()
|
|
36
|
+
return max(floor, midnight(day) - timedelta(days=days - 1))
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def split(low: datetime, high: datetime) -> list[tuple[datetime, datetime]]:
|
|
40
|
+
"""Ranges covering ``low`` to ``high``: halves in whole days, then hours.
|
|
41
|
+
|
|
42
|
+
Oldest first; empty when the range is an hour or less.
|
|
43
|
+
"""
|
|
44
|
+
width = high - low + SECOND
|
|
45
|
+
if width > DAY:
|
|
46
|
+
middle = low + timedelta(days=max(1, width.days // 2))
|
|
47
|
+
return [(low, middle - SECOND), (middle, high)]
|
|
48
|
+
if width <= HOUR:
|
|
49
|
+
return []
|
|
50
|
+
pieces = []
|
|
51
|
+
start = low
|
|
52
|
+
while start <= high:
|
|
53
|
+
pieces.append((start, min(start + HOUR - SECOND, high)))
|
|
54
|
+
start += HOUR
|
|
55
|
+
return pieces
|
|
@@ -0,0 +1,154 @@
|
|
|
1
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
2
|
+
# SPDX-FileCopyrightText: 2026 The Linux Foundation
|
|
3
|
+
"""The step bookkeeping of one `collect` call (design §6.5).
|
|
4
|
+
|
|
5
|
+
`Steps` runs each step's work, ends a step cleanly on a spent budget
|
|
6
|
+
or an outage, and records the first step the budget ran out in, the
|
|
7
|
+
unreadable repositories and the stalled ones. `each` runs one step's
|
|
8
|
+
work for many repositories at once and keeps what finished.
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from __future__ import annotations
|
|
12
|
+
|
|
13
|
+
import logging
|
|
14
|
+
from collections import Counter
|
|
15
|
+
from collections.abc import Awaitable, Coroutine, Iterable, Mapping
|
|
16
|
+
from typing import Any, TypeVar
|
|
17
|
+
|
|
18
|
+
import httpx
|
|
19
|
+
|
|
20
|
+
from github_statistics.client import (
|
|
21
|
+
BudgetExhaustedError,
|
|
22
|
+
GraphQLError,
|
|
23
|
+
Transport,
|
|
24
|
+
TransportError,
|
|
25
|
+
)
|
|
26
|
+
|
|
27
|
+
from .common import SERVER_ERROR, run_concurrently
|
|
28
|
+
from .items import ItemSyncResult
|
|
29
|
+
from .runs import _RunSync
|
|
30
|
+
|
|
31
|
+
log = logging.getLogger(__name__)
|
|
32
|
+
|
|
33
|
+
T = TypeVar("T")
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
class Steps:
|
|
37
|
+
"""The step bookkeeping of one `collect` call."""
|
|
38
|
+
|
|
39
|
+
def __init__(self, transport: Transport) -> None:
|
|
40
|
+
"""Track ``transport``'s budget across the steps."""
|
|
41
|
+
self.transport = transport
|
|
42
|
+
self.exhausted: str | None = None
|
|
43
|
+
self.unreadable: dict[str, str] = {}
|
|
44
|
+
self.stalled: set[str] = set()
|
|
45
|
+
|
|
46
|
+
async def run(self, step: str, work: Awaitable[T]) -> T | None:
|
|
47
|
+
"""Await ``work`` as part of ``step``; ``None`` if it ended early.
|
|
48
|
+
|
|
49
|
+
A spent budget or an outage, a request that outlasted its retries
|
|
50
|
+
or a REST or GraphQL ``5xx``, ends that work, never the run;
|
|
51
|
+
``AuthError``, any other HTTP status error and any other
|
|
52
|
+
``GraphQLError``, such as a refused query, propagate.
|
|
53
|
+
"""
|
|
54
|
+
try:
|
|
55
|
+
value: T | None = await work
|
|
56
|
+
except BudgetExhaustedError as exc:
|
|
57
|
+
log.info("%s step stopped: %s", step, exc)
|
|
58
|
+
self.stop(step)
|
|
59
|
+
value = None
|
|
60
|
+
except TransportError as exc:
|
|
61
|
+
log.warning("%s step ended: %s", step, exc)
|
|
62
|
+
value = None
|
|
63
|
+
except GraphQLError as exc:
|
|
64
|
+
if exc.status is None or exc.status < SERVER_ERROR:
|
|
65
|
+
raise
|
|
66
|
+
log.warning("%s step ended: %s", step, exc)
|
|
67
|
+
value = None
|
|
68
|
+
except httpx.HTTPStatusError as exc:
|
|
69
|
+
if exc.response.status_code < SERVER_ERROR:
|
|
70
|
+
raise
|
|
71
|
+
log.warning("%s step ended: %s", step, exc)
|
|
72
|
+
value = None
|
|
73
|
+
budget = self.transport.budget
|
|
74
|
+
if budget is not None and (budget.rest_exhausted or budget.graphql_exhausted):
|
|
75
|
+
self.stop(step)
|
|
76
|
+
return value
|
|
77
|
+
|
|
78
|
+
async def reading(self, key: str, what: str, work: Coroutine[Any, Any, T]) -> T:
|
|
79
|
+
"""Await one repository's ``work``; on an outage, record ``key`` first.
|
|
80
|
+
|
|
81
|
+
A ``TransportError`` marks ``key`` unreadable for ``what`` and
|
|
82
|
+
propagates, so it still ends the step.
|
|
83
|
+
"""
|
|
84
|
+
try:
|
|
85
|
+
return await work
|
|
86
|
+
except TransportError as exc:
|
|
87
|
+
self.unreadable.setdefault(key, f"{what}: {exc}")
|
|
88
|
+
raise
|
|
89
|
+
|
|
90
|
+
def stop(self, step: str) -> None:
|
|
91
|
+
"""Record ``step`` as the one the budget ran out in, unless one was."""
|
|
92
|
+
if self.exhausted is None:
|
|
93
|
+
log.info("budget spent in the %s step; the next run resumes", step)
|
|
94
|
+
self.exhausted = step
|
|
95
|
+
|
|
96
|
+
def items(self, step: str, results: Mapping[str, ItemSyncResult] | None) -> None:
|
|
97
|
+
"""Record an item sync's unreadable repositories and budget stops.
|
|
98
|
+
|
|
99
|
+
A listing neither drained nor unreadable was stopped by a spent
|
|
100
|
+
budget or a rate limit, which the budget counters may not show.
|
|
101
|
+
"""
|
|
102
|
+
for key, result in (results or {}).items():
|
|
103
|
+
if result.unreadable is not None:
|
|
104
|
+
self.unreadable[key] = f"items: HTTP {result.unreadable}"
|
|
105
|
+
elif not result.drained:
|
|
106
|
+
self.stop(step)
|
|
107
|
+
|
|
108
|
+
def phases(
|
|
109
|
+
self, step: str, syncs: Iterable[_RunSync], finished: Iterable[bool | None]
|
|
110
|
+
) -> None:
|
|
111
|
+
"""Record a budget stop of run phases that ended early and readable.
|
|
112
|
+
|
|
113
|
+
A phase cancelled when its step ended, ``None``, records nothing.
|
|
114
|
+
"""
|
|
115
|
+
for sync, done in zip(syncs, finished, strict=False):
|
|
116
|
+
if done is False and sync.result().unreadable is None:
|
|
117
|
+
self.stop(step)
|
|
118
|
+
|
|
119
|
+
def failed(self, what: str, keys: Iterable[str]) -> None:
|
|
120
|
+
"""Record each repository in ``keys`` as unreadable for ``what``.
|
|
121
|
+
|
|
122
|
+
``keys`` holds a repository once per record of it that failed.
|
|
123
|
+
"""
|
|
124
|
+
for key, count in Counter(keys).items():
|
|
125
|
+
self.unreadable.setdefault(key, f"{what}: {count} failed")
|
|
126
|
+
|
|
127
|
+
def runs(self, key: str, unreadable: int | None, stalled: bool) -> None:
|
|
128
|
+
"""Record a run read's unreadable status and stall."""
|
|
129
|
+
if unreadable is not None:
|
|
130
|
+
self.unreadable.setdefault(key, f"runs: HTTP {unreadable}")
|
|
131
|
+
if stalled:
|
|
132
|
+
self.stalled.add(key)
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
async def each(
|
|
136
|
+
steps: Steps, step: str, works: Iterable[Coroutine[Any, Any, T]]
|
|
137
|
+
) -> list[T | None]:
|
|
138
|
+
"""Await ``works`` concurrently as ``step``; each result, ``None`` if cut short.
|
|
139
|
+
|
|
140
|
+
A failure that ends the step cancels the works still running, but
|
|
141
|
+
those that finished keep their results, so the later steps still
|
|
142
|
+
run for their repositories and report what they found.
|
|
143
|
+
"""
|
|
144
|
+
pending = list(works)
|
|
145
|
+
results: list[T | None] = [None] * len(pending)
|
|
146
|
+
|
|
147
|
+
async def keep(index: int, work: Coroutine[Any, Any, T]) -> None:
|
|
148
|
+
"""Await ``work`` and keep its result at ``index``."""
|
|
149
|
+
results[index] = await work
|
|
150
|
+
|
|
151
|
+
await steps.run(
|
|
152
|
+
step, run_concurrently(keep(i, work) for i, work in enumerate(pending))
|
|
153
|
+
)
|
|
154
|
+
return results
|