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,354 @@
1
+ # SPDX-License-Identifier: Apache-2.0
2
+ # SPDX-FileCopyrightText: 2026 The Linux Foundation
3
+ """One target's budgeted, self-healing sync (design §6.5).
4
+
5
+ `collect` runs the collectors in a fixed order, sharing the
6
+ transport's one budget: scope, public members, the incremental reads,
7
+ enrichment, backfill, then the re-run sweep. The incremental reads and
8
+ enrichment always come before backfill, so yesterday is complete while
9
+ history still fills in. Each step's listing sync ends before the next
10
+ step starts, so enrichment never runs alongside a listing (design §6.3).
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import dataclasses
16
+ from collections.abc import Awaitable, Callable, Coroutine, Iterable, Mapping
17
+ from dataclasses import dataclass, field
18
+ from datetime import UTC, date, datetime, timedelta
19
+ from typing import Any
20
+
21
+ from github_statistics.client import Transport
22
+ from github_statistics.config import Config, Identities, Target, resolve_identities
23
+ from github_statistics.scope import ResolvedScope, apply_scope, resolve_scope
24
+ from github_statistics.store import Store
25
+
26
+ from .common import scope_keys
27
+ from .enrich_items import PER_REPOSITORY, enrich_items
28
+ from .items import ITEMS_METRIC, sync_all_items
29
+ from .jobs import ALL_RUNS, enrich_jobs
30
+ from .members import sync_members
31
+ from .runs import _RunSync
32
+ from .steps import Steps, each
33
+ from .sweep import sweep_runs
34
+
35
+ DAY = timedelta(days=1)
36
+ SCOPE = "scope"
37
+ MEMBERS = "members"
38
+ INCREMENTAL = "incremental"
39
+ ENRICHMENT = "enrichment"
40
+ BACKFILL = "backfill"
41
+ SWEEP = "sweep"
42
+ # The values of the series coverage grades (`render.model.Coverage`).
43
+ COMPLETE, PARTIAL, NONE = "complete", "partial", "none"
44
+
45
+
46
+ @dataclass(frozen=True)
47
+ class MetricCoverage:
48
+ """How many days of the window one charted metric has, by grade (§7.3)."""
49
+
50
+ complete: int
51
+ partial: int
52
+ missing: int
53
+
54
+
55
+ @dataclass(frozen=True)
56
+ class CollectResult:
57
+ """What one target's sync did and how much of the window it holds.
58
+
59
+ ``unreadable`` and ``dropped`` map ``owner/name`` keys to why.
60
+ ``exhausted`` names the first step that ended with the REST or the
61
+ GraphQL budget spent, or in which a collector reported a stop for a
62
+ spent budget or a rate limit, else ``None``. ``stalled`` names repositories
63
+ whose run read a spent budget stopped inside one second.
64
+ ``gap_days`` counts the window's days on which any enabled metric is
65
+ not complete.
66
+ """
67
+
68
+ owner: str
69
+ requests: int
70
+ graphql_points: int
71
+ not_modified: int
72
+ coverage: Mapping[str, MetricCoverage] = field(default_factory=dict)
73
+ gap_days: int = 0
74
+ unreadable: Mapping[str, str] = field(default_factory=dict)
75
+ dropped: Mapping[str, str] = field(default_factory=dict)
76
+ exhausted: str | None = None
77
+ stalled: tuple[str, ...] = ()
78
+
79
+ @property
80
+ def coverage_complete(self) -> bool:
81
+ """Whether every day of every enabled metric is complete."""
82
+ return self.gap_days == 0
83
+
84
+
85
+ def _only(scope: ResolvedScope, keys: Iterable[str]) -> ResolvedScope:
86
+ """``scope`` with only the repositories whose key is among ``keys``."""
87
+ wanted = {key.lower() for key in keys}
88
+ repositories = tuple(
89
+ repository
90
+ for repository in scope.repositories
91
+ if f"{scope.owner}/{repository.name}".lower() in wanted
92
+ )
93
+ return dataclasses.replace(scope, repositories=repositories)
94
+
95
+
96
+ def _refresh(store: Store, keys: Iterable[str]) -> None:
97
+ """Clear the sync state and coverage of ``keys``, keeping their rows."""
98
+ connection = store.connection
99
+ connection.execute("BEGIN")
100
+ try:
101
+ for key in keys:
102
+ for table in ("sync_state", "coverage"):
103
+ connection.execute(f"DELETE FROM {table} WHERE repo = ?", (key,))
104
+ connection.execute("COMMIT")
105
+ except BaseException:
106
+ connection.execute("ROLLBACK")
107
+ raise
108
+
109
+
110
+ def window_coverage(
111
+ store: Store, owner: str, metrics: list[str], start: date, end: date
112
+ ) -> tuple[dict[str, MetricCoverage], int]:
113
+ """Each metric's days from ``start`` to ``end`` by grade; the gap days.
114
+
115
+ A gap day is one on which any of ``metrics`` is not complete.
116
+ """
117
+ # Imported here: the series package imports this one, and loads render.
118
+ from github_statistics.series.coverage import daily_coverage
119
+
120
+ days = [start + DAY * offset for offset in range((end - start).days + 1)]
121
+ scope = [store.in_scope(day) for day in days]
122
+ grades = daily_coverage(store, owner, metrics, days, scope)
123
+ coverage = {
124
+ metric: MetricCoverage(
125
+ complete=values.count(COMPLETE),
126
+ partial=values.count(PARTIAL),
127
+ missing=values.count(NONE),
128
+ )
129
+ for metric, values in grades.items()
130
+ }
131
+ gaps = sum(
132
+ any(grades[metric][index] != COMPLETE for metric in metrics)
133
+ for index in range(len(days))
134
+ )
135
+ return coverage, gaps
136
+
137
+
138
+ @dataclass(frozen=True)
139
+ class _Plan:
140
+ """What one `collect` call reads: the scope, its keys and the window."""
141
+
142
+ scope: ResolvedScope
143
+ keys: list[str]
144
+ window_start: date
145
+ now: datetime
146
+ items: bool
147
+ runs: bool
148
+ jobs: bool
149
+
150
+
151
+ async def _sync(steps: Steps, transport: Transport, store: Store, plan: _Plan) -> None:
152
+ """Steps 3 to 6 of `collect` over ``plan``'s repositories."""
153
+ window, now = {"window_start": plan.window_start}, plan.now
154
+
155
+ def fresh(key: str) -> bool:
156
+ """Whether ``key`` has no item watermark yet, so needs a first sync."""
157
+ state = store.sync_state(key, ITEMS_METRIC)
158
+ return state is None or state.watermark is None
159
+
160
+ first = [key for key in plan.keys if fresh(key)]
161
+ later = [key for key in plan.keys if not fresh(key)]
162
+ syncs = [_RunSync(transport, store, key, **window, now=now) for key in plan.keys]
163
+ current: list[_RunSync] = []
164
+
165
+ async def items(step: str, keys: list[str]) -> None:
166
+ """Sync the items of ``keys``, each under `Steps.reading`."""
167
+ listed = await each(
168
+ steps,
169
+ step,
170
+ (
171
+ steps.reading(
172
+ key,
173
+ "items",
174
+ sync_all_items(
175
+ transport, store, _only(plan.scope, [key]), **window, now=now
176
+ ),
177
+ )
178
+ for key in keys
179
+ ),
180
+ )
181
+ steps.items(step, {k: v for part in listed if part for k, v in part.items()})
182
+
183
+ def guarded(
184
+ sync: _RunSync, phase: Callable[[], Awaitable[None]]
185
+ ) -> Coroutine[Any, Any, bool]:
186
+ """``sync``'s ``phase``, guarded, under `Steps.reading`."""
187
+ return steps.reading(sync.key, "runs", sync.guarded(phase))
188
+
189
+ if plan.items and later:
190
+ await items(INCREMENTAL, later)
191
+ if plan.runs:
192
+ finished = await each(
193
+ steps, INCREMENTAL, (guarded(sync, sync.recent) for sync in syncs)
194
+ )
195
+ steps.phases(INCREMENTAL, syncs, finished)
196
+ current = [s for s, done in zip(syncs, finished, strict=True) if done]
197
+
198
+ await _enrich(steps, transport, store, plan)
199
+
200
+ if plan.items and first:
201
+ await items(BACKFILL, first)
202
+ if current:
203
+ backfilled = await each(
204
+ steps, BACKFILL, (guarded(sync, sync.backfill) for sync in current)
205
+ )
206
+ steps.phases(BACKFILL, current, backfilled)
207
+ for sync in syncs:
208
+ result = sync.result()
209
+ steps.runs(sync.key, result.unreadable, result.stalled)
210
+
211
+ if current:
212
+ await _sweep(steps, transport, store, [sync.key for sync in current], now)
213
+
214
+
215
+ async def _enrich(
216
+ steps: Steps, transport: Transport, store: Store, plan: _Plan
217
+ ) -> None:
218
+ """Step 4: enrich items, then count jobs; report the repositories they failed.
219
+
220
+ An id that failed alone, unlike one the budget left, makes the
221
+ repository holding it unreadable.
222
+ """
223
+ if plan.items:
224
+ enriched = await steps.run(
225
+ ENRICHMENT, enrich_items(transport, store, plan.keys)
226
+ )
227
+ if enriched is not None and enriched.failed:
228
+ ids = set(enriched.failed)
229
+ steps.failed(
230
+ "item enrichment",
231
+ (
232
+ item.repo
233
+ for key in plan.keys
234
+ for item in store.items_needing_enrichment(key, PER_REPOSITORY)
235
+ if item.node_id in ids
236
+ ),
237
+ )
238
+ if plan.jobs:
239
+ counted = await steps.run(ENRICHMENT, enrich_jobs(transport, store, plan.keys))
240
+ if counted is not None and counted.failed:
241
+ ids = set(counted.failed)
242
+ runs = store.runs_needing_jobs(ALL_RUNS)
243
+ steps.failed("job counts", (r.repo for r in runs if r.node_id in ids))
244
+
245
+
246
+ async def _sweep(
247
+ steps: Steps, transport: Transport, store: Store, keys: list[str], now: datetime
248
+ ) -> None:
249
+ """Step 6: the re-run sweep of ``keys``, where due."""
250
+ sweeps = await each(
251
+ steps,
252
+ SWEEP,
253
+ (
254
+ steps.reading(
255
+ key, "runs", sweep_runs(transport, store, *key.split("/", 1), now=now)
256
+ )
257
+ for key in keys
258
+ ),
259
+ )
260
+ for swept in sweeps:
261
+ if swept is None:
262
+ continue
263
+ steps.runs(swept.repo, swept.unreadable, swept.stalled)
264
+ if swept.due and not swept.swept and swept.unreadable is None:
265
+ steps.stop(SWEEP)
266
+
267
+
268
+ async def collect(
269
+ config: Config,
270
+ target: Target,
271
+ *,
272
+ now: datetime,
273
+ transport: Transport,
274
+ store: Store,
275
+ identities: Identities | None = None,
276
+ refresh: bool = False,
277
+ until: date | None = None,
278
+ ) -> CollectResult:
279
+ """Sync ``target`` into ``store`` in the order design §6.5 gives.
280
+
281
+ The window is ``config.window.days`` days ending on ``until``,
282
+ by default the day before ``now``, in UTC; ``now`` stays the time
283
+ of the reads. Steps: resolve the scope and apply it to the store;
284
+ read public members; the incremental reads of items, from
285
+ repositories with a watermark, then of runs; enrich items, then
286
+ count jobs; backfill, first item syncs then runs; the re-run sweep,
287
+ where due. A disabled metric's collectors do not run. An empty scope
288
+ makes no call after its resolution, and a scope the budget stops
289
+ applies nothing. A repository whose read outlasts its retries is
290
+ unreadable, and the outage ends its step; the repositories that
291
+ finished that step go on to the later ones. A repository with an
292
+ item or a run whose enrichment read fails alone is unreadable too.
293
+ ``refresh`` clears the
294
+ scope's sync state and coverage first, so the window is read again.
295
+ One repository failing never fails the run, and a spent budget ends
296
+ the steps cleanly; ``AuthError`` propagates.
297
+ """
298
+ today = now.astimezone(UTC).date()
299
+ end = until or today - DAY
300
+ start = end - DAY * (config.window.days - 1)
301
+ metrics = config.metrics
302
+ enabled = [f.name for f in dataclasses.fields(metrics) if getattr(metrics, f.name)]
303
+ steps = Steps(transport)
304
+ dropped: dict[str, str] = {}
305
+
306
+ known = store.stored_repositories()
307
+ scope = await steps.run(SCOPE, resolve_scope(transport, target, known=known))
308
+ owner = target.owner if scope is None else scope.owner
309
+ if scope is not None:
310
+ apply_scope(store, scope, today=today, window_start=start)
311
+ dropped = {f"{owner}/{drop.name}": drop.reason for drop in scope.dropped}
312
+ for name in scope.unresolved:
313
+ steps.unreadable[f"{owner}/{name}"] = "scope: read failed"
314
+ keys = scope_keys(store, scope, now)
315
+ if refresh:
316
+ _refresh(store, keys)
317
+ if keys:
318
+ orgs = resolve_identities(target, config, identities).member_orgs.values
319
+ await steps.run(
320
+ MEMBERS,
321
+ sync_members(
322
+ transport,
323
+ store,
324
+ orgs,
325
+ owner=owner,
326
+ owner_type=scope.owner_type,
327
+ today=today,
328
+ ),
329
+ )
330
+ plan = _Plan(
331
+ scope,
332
+ keys,
333
+ start,
334
+ now,
335
+ items=metrics.pull_requests or metrics.issues,
336
+ runs=metrics.workflows or metrics.workflow_outcomes,
337
+ jobs=metrics.workflows,
338
+ )
339
+ await _sync(steps, transport, store, plan)
340
+
341
+ coverage, gaps = window_coverage(store, owner, enabled, start, end)
342
+ stats = transport.stats
343
+ return CollectResult(
344
+ owner=owner,
345
+ requests=stats.requests,
346
+ graphql_points=stats.graphql_cost,
347
+ not_modified=stats.not_modified,
348
+ coverage=coverage,
349
+ gap_days=gaps,
350
+ unreadable=dict(sorted(steps.unreadable.items())),
351
+ dropped=dropped,
352
+ exhausted=steps.exhausted,
353
+ stalled=tuple(sorted(steps.stalled)),
354
+ )