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,238 @@
1
+ # SPDX-License-Identifier: Apache-2.0
2
+ # SPDX-FileCopyrightText: 2026 The Linux Foundation
3
+ """Collect issues and pull requests from the issues listing (design §6.2).
4
+
5
+ One listing per repository, ordered by ``updated_at``, feeds both the
6
+ ``issues`` and the ``pull_requests`` metrics. Each page is stored with
7
+ the watermark it advances to in one transaction, so an interrupted sync
8
+ resumes from a consistent point. Coverage is all-or-nothing per sync:
9
+ an item read late in the listing can carry an event from any earlier
10
+ day, so only a listing read to its end proves any day complete.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import dataclasses
16
+ import logging
17
+ from dataclasses import dataclass
18
+ from datetime import UTC, date, datetime, time, timedelta
19
+ from typing import Any
20
+ from urllib.parse import quote
21
+
22
+ import httpx
23
+
24
+ from github_statistics.client import BudgetExhaustedError, Transport, get_paged
25
+ from github_statistics.scope import ResolvedScope
26
+ from github_statistics.store import Item, Store, SyncState
27
+
28
+ from .common import run_concurrently, scope_keys, unreadable_status
29
+
30
+ log = logging.getLogger(__name__)
31
+
32
+ # The sync state of the listing both metrics share.
33
+ ITEMS_METRIC = "items"
34
+ ISSUES_METRIC = "issues"
35
+ PULL_REQUESTS_METRIC = "pull_requests"
36
+ COVERAGE_METRICS = (ISSUES_METRIC, PULL_REQUESTS_METRIC)
37
+
38
+ GHOST = "ghost"
39
+ _OVERLAP = timedelta(seconds=1)
40
+
41
+
42
+ @dataclass(frozen=True)
43
+ class ItemSyncResult:
44
+ """What one repository's item sync did.
45
+
46
+ ``drained`` is true when the listing was read to its end, which is
47
+ when coverage is added. ``unreadable`` holds the HTTP status that
48
+ made the repository unreadable for this run (a ``403`` that is not
49
+ a rate limit, a ``404``, a ``410``, or a ``5xx`` the transport's
50
+ retries did not clear), and is ``None`` otherwise.
51
+ """
52
+
53
+ repo: str
54
+ items: int
55
+ pages: int
56
+ drained: bool
57
+ unreadable: int | None = None
58
+
59
+
60
+ def _parse(text: str | None) -> datetime | None:
61
+ """A GitHub timestamp as an aware `datetime`, or ``None``."""
62
+ return None if text is None else datetime.fromisoformat(text)
63
+
64
+
65
+ def _item(repo: str, data: dict[str, Any]) -> Item:
66
+ """The stored record of one listed issue or pull request.
67
+
68
+ Reads only the fields the store keeps: never a title, a body, labels
69
+ or ``author_association``.
70
+ """
71
+ pull_request = data.get("pull_request")
72
+ merged_at = None if pull_request is None else pull_request.get("merged_at")
73
+ user = data.get("user")
74
+ return Item(
75
+ repo=repo,
76
+ number=int(data["number"]),
77
+ node_id=data["node_id"],
78
+ kind="issue" if pull_request is None else "pr",
79
+ created_at=datetime.fromisoformat(data["created_at"]),
80
+ closed_at=_parse(data.get("closed_at")),
81
+ merged_at=_parse(merged_at),
82
+ author=GHOST if user is None else user["login"],
83
+ author_type=None if user is None else user.get("type"),
84
+ updated_at=datetime.fromisoformat(data["updated_at"]),
85
+ )
86
+
87
+
88
+ def _start(state: SyncState, window_start: date) -> tuple[SyncState, datetime]:
89
+ """The state to sync from and the ``since`` to list from.
90
+
91
+ A scan starts one second before the window start, 00:00 UTC, so an
92
+ item updated at that instant is listed whether ``since`` includes
93
+ it or not, and records that start as ``oldest``: the scan's chain of
94
+ listings, finished or not, has read nothing older. A later sync
95
+ lists from one second before the watermark, unless the window now
96
+ starts before ``oldest``, which a wider window or a prune (which
97
+ raises ``oldest`` to its day) can leave. Those days were never
98
+ listed by this chain, or a prune has since dropped them, so the
99
+ scan starts over from this window. Coverage an earlier chain left
100
+ proves nothing about this one, so it is not consulted. A scan whose
101
+ watermark is older than the window's midnight also starts over,
102
+ rather than rereading items the window no longer needs or restoring
103
+ pruned ones; its new ``oldest`` keeps a later, wider window checked
104
+ against what this scan listed.
105
+ """
106
+ midnight = datetime.combine(window_start, time(), tzinfo=UTC)
107
+ start = midnight - _OVERLAP
108
+ behind = state.oldest is None or midnight < state.oldest
109
+ stale = state.watermark is not None and state.watermark < midnight
110
+ if state.watermark is None or behind or stale:
111
+ restart = dataclasses.replace(
112
+ state, watermark=None, oldest=start, last_sync_at=None
113
+ )
114
+ return restart, start
115
+ return state, state.watermark - _OVERLAP
116
+
117
+
118
+ def _add_coverage(store: Store, repo: str, window_start: date, now: datetime) -> None:
119
+ """Cover each metric from ``window_start`` to the day before ``now``.
120
+
121
+ A drained listing has read every item updated since a scan that
122
+ started at or before the window start, so it proves the whole window.
123
+ """
124
+ last = now.astimezone(UTC).date() - timedelta(days=1)
125
+ if window_start <= last:
126
+ for metric in COVERAGE_METRICS:
127
+ store.add_coverage(repo, metric, window_start, last)
128
+
129
+
130
+ async def sync_items(
131
+ transport: Transport,
132
+ store: Store,
133
+ owner: str,
134
+ repo: str,
135
+ *,
136
+ window_start: date,
137
+ now: datetime,
138
+ ) -> ItemSyncResult:
139
+ """Sync the issues and pull requests of ``owner/repo`` into ``store``.
140
+
141
+ The first sync lists from one second before ``window_start`` at
142
+ 00:00 UTC; later ones from one second before the stored watermark,
143
+ unless the window now starts before the days already listed. A
144
+ restart of a stored sync is saved before the first page; one for a
145
+ wider window also marks the pull requests created before the
146
+ earlier scan's start for review enrichment in the same transaction,
147
+ since a prune may have dropped their older reviews.
148
+ There is no ``budget`` argument: the budget is the one the caller
149
+ configures on ``transport`` (design §6.5), so it cannot disagree
150
+ with the one the transport charges.
151
+ The transport checks its budget before each page, after refusing a
152
+ token GitHub rejected with ``AuthError``; when the budget is spent,
153
+ the transport raises ``BudgetExhaustedError``, or an
154
+ unbudgeted transport returns a rate limit its retries did not clear,
155
+ the sync stops with ``drained=False``. Any other ``403``, a ``404``,
156
+ ``410`` or a ``5xx``
157
+ left after the transport's retries marks the repository unreadable
158
+ with no coverage change. Coverage of both metrics, over the window,
159
+ is added only when the listing is read to its end.
160
+ """
161
+ key = f"{owner}/{repo}"
162
+ saved = store.sync_state(key, ITEMS_METRIC)
163
+ previous = saved or SyncState(key, ITEMS_METRIC)
164
+ state, since = _start(previous, window_start)
165
+ if saved is not None and state is not previous:
166
+ oldest = saved.oldest
167
+ wider = (
168
+ oldest is not None and state.oldest is not None and state.oldest < oldest
169
+ )
170
+ # A prune may have dropped reviews older than the earlier scan's start.
171
+ store.restart_item_sync(state, oldest if wider else None)
172
+ path = "/".join(quote(part, safe="") for part in ("repos", owner, repo, "issues"))
173
+ params = {
174
+ "state": "all",
175
+ "sort": "updated",
176
+ "direction": "asc",
177
+ "per_page": 100,
178
+ "since": since.strftime("%Y-%m-%dT%H:%M:%SZ"),
179
+ }
180
+ stored = pages = 0
181
+ drained = False
182
+ try:
183
+ async for page, _response in get_paged(transport, "/" + path, params):
184
+ pages += 1
185
+ items = [_item(key, data) for data in page]
186
+ if items:
187
+ state = dataclasses.replace(state, watermark=items[-1].updated_at)
188
+ store.store_item_page(items, state)
189
+ stored += len(items)
190
+ drained = True
191
+ except BudgetExhaustedError as exc:
192
+ log.info("stopped syncing items of %s: %s", key, exc)
193
+ except httpx.HTTPStatusError as exc:
194
+ status = unreadable_status(exc)
195
+ if status is None:
196
+ log.info("stopped syncing items of %s: rate limited", key)
197
+ else:
198
+ log.warning("cannot read items of %s: HTTP %s", key, status)
199
+ return ItemSyncResult(key, stored, pages, drained=False, unreadable=status)
200
+ if drained:
201
+ store.set_sync_state(dataclasses.replace(state, last_sync_at=now))
202
+ _add_coverage(store, key, window_start, now)
203
+ return ItemSyncResult(key, stored, pages, drained)
204
+
205
+
206
+ async def sync_all_items(
207
+ transport: Transport,
208
+ store: Store,
209
+ scope: ResolvedScope,
210
+ *,
211
+ window_start: date,
212
+ now: datetime,
213
+ ) -> dict[str, ItemSyncResult]:
214
+ """Sync every repository in ``scope`` concurrently; results by ``owner/name``.
215
+
216
+ The transport's semaphore bounds the concurrency. Repositories with
217
+ a watermark, the quick incremental work, start before those without.
218
+ A repository keeps the spelling the store's scope holds for it, as
219
+ names compare without case, so a rename in case alone keeps its
220
+ watermark, items and coverage under one key. An error that stops a
221
+ repository, ``AuthError`` first, propagates as itself, not wrapped
222
+ in an ``ExceptionGroup``, and cancels the other repositories.
223
+ """
224
+
225
+ def fresh(key: str) -> bool:
226
+ """Whether ``key`` has no watermark yet."""
227
+ state = store.sync_state(key, ITEMS_METRIC)
228
+ return state is None or state.watermark is None
229
+
230
+ syncs = []
231
+ for key in sorted(scope_keys(store, scope, now), key=fresh):
232
+ owner, _, name = key.partition("/")
233
+ syncs.append(
234
+ sync_items(
235
+ transport, store, owner, name, window_start=window_start, now=now
236
+ )
237
+ )
238
+ return {result.repo: result for result in await run_concurrently(syncs)}
@@ -0,0 +1,194 @@
1
+ # SPDX-License-Identifier: Apache-2.0
2
+ # SPDX-FileCopyrightText: 2026 The Linux Foundation
3
+ """Count the jobs of each concluded workflow run (design §6.4).
4
+
5
+ One GraphQL ``nodes(ids:)`` query reads fifty runs and the check runs
6
+ of each run's latest attempt (``checkType: LATEST``), what the run's
7
+ page shows. The counts of a batch are stored in one transaction, and
8
+ the days whose runs all hold a count regain jobs coverage.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import logging
14
+ from collections.abc import Iterable
15
+ from dataclasses import dataclass
16
+ from typing import Any
17
+
18
+ from github_statistics.client import (
19
+ BudgetExhaustedError,
20
+ GraphQLError,
21
+ Transport,
22
+ TransportError,
23
+ batched,
24
+ graphql,
25
+ )
26
+ from github_statistics.store import Store
27
+
28
+ from .enrich_items import BATCH_COST, BATCH_SIZE, PAGE_COST, _not_found
29
+
30
+ log = logging.getLogger(__name__)
31
+
32
+ # More runs than a store holds, so a run sees every one needing a count.
33
+ ALL_RUNS = 100_000_000
34
+
35
+ JOBS_QUERY = """
36
+ query($ids: [ID!]!) {
37
+ rateLimit { cost remaining }
38
+ nodes(ids: $ids) {
39
+ ... on WorkflowRun {
40
+ id
41
+ databaseId
42
+ checkSuite { checkRuns(filterBy: {checkType: LATEST}) { totalCount } }
43
+ }
44
+ }
45
+ }
46
+ """
47
+
48
+
49
+ @dataclass(frozen=True)
50
+ class JobsResult:
51
+ """What one job-count run did.
52
+
53
+ ``runs`` counts the runs given a job count. ``failed`` holds the
54
+ node ids that failed alone and ``remaining`` those not reached; both
55
+ are read again on the next run.
56
+ """
57
+
58
+ runs: int
59
+ failed: tuple[str, ...] = ()
60
+ remaining: tuple[str, ...] = ()
61
+
62
+
63
+ class _Stopped(BudgetExhaustedError):
64
+ """Ends the batching early, so ``batched`` returns the ids not reached."""
65
+
66
+
67
+ def _forbidden(exc: GraphQLError) -> bool:
68
+ """Whether GitHub refused to read a check suite: the token lacks ``checks``."""
69
+ return any(
70
+ isinstance(error, dict)
71
+ and error.get("type") == "FORBIDDEN"
72
+ and "checkSuite" in (error.get("path") or [])
73
+ for error in exc.errors
74
+ )
75
+
76
+
77
+ def _count(node: Any) -> int:
78
+ """The job count of ``node``; ``0`` for a deleted run or one without a suite."""
79
+ suite = node.get("checkSuite") if isinstance(node, dict) else None
80
+ if not isinstance(suite, dict):
81
+ return 0
82
+ total = (suite.get("checkRuns") or {}).get("totalCount")
83
+ return total if isinstance(total, int) else 0
84
+
85
+
86
+ async def _read(transport: Transport, ids: list[str]) -> list[Any]:
87
+ """The nodes of ``ids``, in order; ``[None]`` for one id GitHub cannot find."""
88
+ estimate = BATCH_COST if len(ids) > 1 else PAGE_COST
89
+ try:
90
+ data = await graphql(
91
+ transport, JOBS_QUERY, {"ids": ids}, cost_estimate=estimate
92
+ )
93
+ except GraphQLError as exc:
94
+ if _forbidden(exc):
95
+ log.warning(
96
+ "GitHub refused to read check suites: the token needs"
97
+ " checks: read; job counts are left for a later run"
98
+ )
99
+ raise _Stopped("checks: read is missing") from exc
100
+ if len(ids) == 1 and _not_found(exc, ["nodes", 0]):
101
+ return [None]
102
+ raise
103
+ except TransportError as exc:
104
+ log.warning(
105
+ "stopped counting jobs at %s: %s; it and those after it"
106
+ " are read again next run",
107
+ ids[0],
108
+ exc,
109
+ )
110
+ raise _Stopped(str(exc)) from exc
111
+ return list(data.get("nodes") or [None] * len(ids))
112
+
113
+
114
+ async def enrich_jobs(
115
+ transport: Transport, store: Store, repos: Iterable[str]
116
+ ) -> JobsResult:
117
+ """Store the job count of every concluded run of ``repos`` that has none.
118
+
119
+ ``repos`` are the store's ``owner/name`` keys of the resolved scope;
120
+ runs kept for a repository out of scope are not read, since the
121
+ token may no longer reach them, and keep their stored history.
122
+ Runs with a conclusion and no job count go fifty to a query, the
123
+ newest first, so recent days complete first and a cold start fills
124
+ in backwards. A run still in progress waits until the runs collector
125
+ sees it conclude. The count is the check runs of the run's latest
126
+ attempt; a run GitHub no longer finds, or one without a check suite,
127
+ stores ``0`` so it is not read again. The store clears a run's count
128
+ when its status, conclusion or attempt changes, so a re-run is
129
+ counted again here. Each repository's jobs coverage then becomes
130
+ its runs coverage less the days holding a run without a count.
131
+
132
+ There is no ``budget`` argument: the budget is the one on
133
+ ``transport`` (design §6.5), charged the cost each query reports.
134
+ When fewer points are left than a batch may cost, one run is read
135
+ alone; when the budget runs out, counting stops cleanly with the
136
+ ids it did not reach in ``remaining``, and a run that completes
137
+ nothing logs a warning naming ``budget.graphql_points``. A batch
138
+ that fails is halved; an id that fails alone is logged and left in
139
+ ``failed`` for the next run. A ``FORBIDDEN`` check suite, a token
140
+ without ``checks: read``, logs one warning and ends the step, as
141
+ does a transport error; the counts stored so far are kept, and no
142
+ budget warning follows even when the refused query took the last
143
+ point.
144
+ """
145
+ wanted = set(repos)
146
+ runs = [
147
+ run
148
+ for run in store.runs_needing_jobs(ALL_RUNS)
149
+ if run.conclusion and run.repo in wanted
150
+ ]
151
+ runs.sort(key=lambda run: (run.created_at, run.id), reverse=True)
152
+ ids = {run.node_id: run.id for run in runs}
153
+ done: set[str] = set()
154
+ stopped = False
155
+
156
+ async def fetch(chunk: list[str]) -> None:
157
+ """Read one batch and store its counts."""
158
+ nonlocal stopped
159
+ # A last point cannot cover a batch but reads one run.
160
+ budget = transport.budget
161
+ last = (
162
+ len(chunk) > 1 and budget is not None and budget.graphql_left < BATCH_COST
163
+ )
164
+ if last:
165
+ chunk = chunk[:1]
166
+ try:
167
+ nodes = await _read(transport, chunk)
168
+ except _Stopped:
169
+ stopped = True
170
+ raise
171
+ counts = {ids[n]: _count(node) for n, node in zip(chunk, nodes, strict=True)}
172
+ store.set_job_counts(counts)
173
+ done.update(chunk)
174
+ if last:
175
+ raise BudgetExhaustedError("one GraphQL point left; read one run")
176
+
177
+ def describe(chunk: list[str]) -> str:
178
+ """Name a batch in the log."""
179
+ return f"{len(chunk)} runs from {chunk[0]}"
180
+
181
+ out = await batched(list(ids), BATCH_SIZE, fetch, describe)
182
+ for node_id in out.failed:
183
+ log.warning("could not count the jobs of run %d (%s)", ids[node_id], node_id)
184
+ store.restore_jobs_coverage()
185
+ remaining = tuple(node_id for node_id in out.remaining if node_id not in done)
186
+ budget = transport.budget
187
+ # A step ended by _read has logged its own cause; more points cannot help.
188
+ if remaining and not done and not stopped and budget and budget.graphql_exhausted:
189
+ log.warning(
190
+ "the GraphQL budget was too small to count the jobs of any run;"
191
+ " %d wait for the next run: raise budget.graphql_points",
192
+ len(remaining),
193
+ )
194
+ return JobsResult(runs=len(done), failed=tuple(out.failed), remaining=remaining)
@@ -0,0 +1,42 @@
1
+ # SPDX-License-Identifier: Apache-2.0
2
+ # SPDX-FileCopyrightText: 2026 The Linux Foundation
3
+ """Workflow runs as the Actions listing returns them (design §6.4)."""
4
+
5
+ from __future__ import annotations
6
+
7
+ from collections.abc import Iterable
8
+ from datetime import datetime
9
+ from typing import Any
10
+
11
+ from github_statistics.store import Run
12
+
13
+
14
+ def listed_run(repo: str, data: dict[str, Any]) -> Run:
15
+ """The stored record of one listed run.
16
+
17
+ The actor is ``triggering_actor``, falling back to ``actor``; what a
18
+ scheduled run's actor means is for classification (design §7.1).
19
+ """
20
+ actor = data.get("triggering_actor") or data.get("actor")
21
+ return Run(
22
+ id=int(data["id"]),
23
+ node_id=data["node_id"],
24
+ repo=repo,
25
+ workflow_path=data["path"],
26
+ event=data["event"],
27
+ status=data["status"],
28
+ conclusion=data.get("conclusion"),
29
+ created_at=datetime.fromisoformat(data["created_at"]),
30
+ actor=None if actor is None else actor["login"],
31
+ actor_type=None if actor is None else actor.get("type"),
32
+ attempt=int(data.get("run_attempt", 1)),
33
+ )
34
+
35
+
36
+ def reaches(runs: Iterable[Run], since: datetime) -> bool:
37
+ """Whether any of ``runs`` was created before ``since``.
38
+
39
+ Strictly before: runs sharing the second of ``since`` may run on
40
+ past the page that holds the first of them.
41
+ """
42
+ return any(run.created_at < since for run in runs)
@@ -0,0 +1,70 @@
1
+ # SPDX-License-Identifier: Apache-2.0
2
+ # SPDX-FileCopyrightText: 2026 The Linux Foundation
3
+ """Read the public members of each member organisation (design §7.1).
4
+
5
+ The privacy rule lives here: the collector reads
6
+ ``/orgs/{org}/public_members`` and nothing else, so the tool never
7
+ learns a private membership, whatever the token may see.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import logging
13
+ from collections.abc import Iterable
14
+ from datetime import date
15
+ from urllib.parse import quote
16
+
17
+ import httpx
18
+
19
+ from github_statistics.client import (
20
+ BudgetExhaustedError,
21
+ Transport,
22
+ TransportError,
23
+ get_paged,
24
+ )
25
+ from github_statistics.store import Store
26
+
27
+ log = logging.getLogger(__name__)
28
+
29
+ USER = "User"
30
+
31
+
32
+ async def sync_members(
33
+ transport: Transport,
34
+ store: Store,
35
+ member_orgs: Iterable[str],
36
+ *,
37
+ owner: str,
38
+ owner_type: str,
39
+ today: date,
40
+ ) -> dict[str, int]:
41
+ """Store the public members of each of ``member_orgs``; counts by organisation.
42
+
43
+ Every page of ``GET /orgs/{org}/public_members`` is read, then the
44
+ logins replace those stored (`Store.replace_members`). When
45
+ ``owner_type`` is ``User``, ``owner`` names no organisation and is
46
+ not read: the classifier counts the owner a member itself. A read
47
+ that fails, by HTTP status, transport error or spent budget, keeps
48
+ the stored list, logs a warning and leaves the organisation out of
49
+ the result. A spent budget, or a rate limit that outlasts the
50
+ retries, ends the step: ``BudgetExhaustedError`` propagates once the
51
+ lists read before it are stored. ``AuthError`` propagates.
52
+ """
53
+ counts: dict[str, int] = {}
54
+ for org in dict.fromkeys(member_orgs):
55
+ if owner_type == USER and org.lower() == owner.lower():
56
+ continue
57
+ path = f"/orgs/{quote(org, safe='')}/public_members"
58
+ logins: list[str] = []
59
+ try:
60
+ async for page, _response in get_paged(transport, path, {"per_page": 100}):
61
+ logins.extend(member["login"] for member in page)
62
+ except BudgetExhaustedError as exc:
63
+ log.warning("kept the stored members of %s: %s", org, exc)
64
+ raise
65
+ except (httpx.HTTPStatusError, TransportError) as exc:
66
+ log.warning("kept the stored members of %s: %s", org, exc)
67
+ continue
68
+ store.replace_members(org, logins, today)
69
+ counts[org] = len(logins)
70
+ return counts
@@ -0,0 +1,124 @@
1
+ # SPDX-License-Identifier: Apache-2.0
2
+ # SPDX-FileCopyrightText: 2026 The Linux Foundation
3
+ """Read a repository's runs in ``created=A..B`` date slices (design §6.4).
4
+
5
+ The run sync's incremental read, backfill and weekly re-run sweep read
6
+ through it. The ``runs_gap`` sync state's ``watermark``
7
+ holds the end of the newest range read only up to the listing cap, and
8
+ its ``oldest`` the start of the oldest such range.
9
+
10
+ A read the budget stops between pages resumes from the second above the
11
+ oldest run read. If more runs share that second than the budget can page
12
+ through, every sync re-reads the same pages and never passes them. That
13
+ needs over a hundred runs created in one second and a budget that runs
14
+ out among their pages on every sync. The collector accepts that as a
15
+ limit (#57) rather than keep a page cursor for the second in the store:
16
+ such a read logs a warning and sets ``stalled``.
17
+ """
18
+
19
+ from __future__ import annotations
20
+
21
+ import logging
22
+ from collections.abc import Callable
23
+ from datetime import datetime
24
+ from urllib.parse import quote
25
+
26
+ from github_statistics.client import BudgetExhaustedError, Transport, get_paged
27
+ from github_statistics.store import Store, SyncState
28
+
29
+ from .listed import listed_run
30
+ from .slices import SECOND, split, timestamp
31
+
32
+ log = logging.getLogger(__name__)
33
+
34
+ GAP_METRIC = "runs_gap"
35
+ LISTING_CAP = 1000
36
+ PER_PAGE = 100
37
+ RUNS_KEY = "workflow_runs"
38
+ Checkpoint = Callable[[datetime, bool], None]
39
+
40
+
41
+ class SliceReader:
42
+ """Reads the runs of one repository by date slice, counting what it reads."""
43
+
44
+ def __init__(self, transport: Transport, store: Store, key: str) -> None:
45
+ """Prepare to read the runs of ``key`` (``owner/name``)."""
46
+ owner, _, name = key.partition("/")
47
+ parts = ("repos", owner, name, "actions", "runs")
48
+ self.path = "/" + "/".join(quote(part, safe="") for part in parts)
49
+ self.transport = transport
50
+ self.store = store
51
+ self.key = key
52
+ gap = store.sync_state(key, GAP_METRIC)
53
+ self.gap = None if gap is None else gap.watermark
54
+ self.gap_low = None if gap is None else gap.oldest
55
+ self.runs = 0
56
+ self.pages = 0
57
+ self.stalled = False
58
+
59
+ async def read(
60
+ self, low: datetime, high: datetime, checkpoint: Checkpoint
61
+ ) -> tuple[int, bool]:
62
+ """Store every run created from ``low`` to ``high``; (count, complete).
63
+
64
+ A range over the listing cap is read in `split` parts, newest
65
+ first; an hour still over it is read up to the cap and is
66
+ incomplete. ``checkpoint`` gets each part once read and, when a
67
+ spent budget stops the paging, the second above the oldest run
68
+ read: runs sharing that second may lie on the unread page. When
69
+ that is no earlier than the second above ``high``, the read made
70
+ no progress and is ``stalled``.
71
+ """
72
+ created = f"{timestamp(low)}..{timestamp(high)}"
73
+ params = {"per_page": PER_PAGE, "created": created}
74
+ read = 0
75
+ first = True
76
+ capped = False
77
+ bottom: datetime | None = None
78
+ pieces: list[tuple[datetime, datetime]] = []
79
+ paged = get_paged(self.transport, self.path, params, items_key=RUNS_KEY)
80
+ try:
81
+ async for page, response in paged:
82
+ self.pages += 1
83
+ if first:
84
+ first = False
85
+ if int(response.json()["total_count"]) > LISTING_CAP:
86
+ pieces = split(low, high)
87
+ if pieces:
88
+ break
89
+ log.warning("over %d runs of %s", LISTING_CAP, self.key)
90
+ capped = True
91
+ self._mark_gap(low, high)
92
+ runs = [listed_run(self.key, data) for data in page]
93
+ self.store.upsert_runs(runs)
94
+ read += len(runs)
95
+ self.runs += len(runs)
96
+ bottom = min((run.created_at for run in runs), default=bottom)
97
+ except BudgetExhaustedError:
98
+ if bottom is not None:
99
+ if bottom >= high:
100
+ log.warning(
101
+ "budget spent within runs of %s created at %s; "
102
+ "the next sync re-reads them",
103
+ self.key,
104
+ timestamp(high),
105
+ )
106
+ self.stalled = True
107
+ checkpoint(bottom + SECOND, True)
108
+ raise
109
+ if not pieces:
110
+ return read, not capped
111
+ complete = True
112
+ for start, end in reversed(pieces):
113
+ count, done = await self.read(start, end, checkpoint)
114
+ read += count
115
+ complete = complete and done
116
+ checkpoint(start, done)
117
+ return read, complete
118
+
119
+ def _mark_gap(self, low: datetime, high: datetime) -> None:
120
+ """Record that runs created from ``low`` to ``high`` were not all read."""
121
+ self.gap = high if self.gap is None else max(self.gap, high)
122
+ self.gap_low = low if self.gap_low is None else min(self.gap_low, low)
123
+ state = SyncState(self.key, GAP_METRIC, watermark=self.gap, oldest=self.gap_low)
124
+ self.store.set_sync_state(state)