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,126 @@
1
+ # SPDX-License-Identifier: Apache-2.0
2
+ # SPDX-FileCopyrightText: 2026 The Linux Foundation
3
+ """The ``render`` command: every target's charts from the store (design §4.2, §8.4).
4
+
5
+ Needs no token and sends no request. Each store opens read-only, so
6
+ rendering never creates, rebuilds or writes one; a missing or stale
7
+ store fails with a message naming ``collect``, and one SQLite cannot
8
+ read fails naming its path. A repository selection cannot narrow a
9
+ store, so a selection that drops a repository the store held in scope
10
+ during the window fails rather than chart that repository under the
11
+ selection's title. Standard output lists the files written, one per
12
+ line.
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ import sqlite3
18
+ from collections.abc import Iterator, Sequence
19
+ from datetime import UTC, date, datetime, timedelta
20
+ from fnmatch import fnmatchcase
21
+ from pathlib import Path
22
+
23
+ import typer
24
+
25
+ from github_statistics.config import ConfigError, Resolution, Target, default_cache_dir
26
+ from github_statistics.store import store_path
27
+
28
+ from .common import API_HOST, ReadOnlyStore, StaleStoreError, fail
29
+ from .options import SharedOptions, shared_options
30
+
31
+
32
+ def _matches(name: str, patterns: tuple[str, ...]) -> bool:
33
+ """Whether ``name`` matches any of ``patterns``, ignoring case, as `collect` does."""
34
+ return any(fnmatchcase(name.lower(), pattern.lower()) for pattern in patterns)
35
+
36
+
37
+ def _unselected(target: Target, repositories: list[str]) -> list[str]:
38
+ """The ``owner/name`` keys in ``repositories`` that ``target``'s selection drops."""
39
+ dropped = []
40
+ for repo in repositories:
41
+ name = repo.partition("/")[2]
42
+ if (target.include and not _matches(name, target.include)) or _matches(
43
+ name, target.exclude
44
+ ):
45
+ dropped.append(repo)
46
+ return dropped
47
+
48
+
49
+ def render_targets(
50
+ resolution: Resolution,
51
+ targets: Sequence[Target],
52
+ *,
53
+ until: date,
54
+ now: datetime,
55
+ ) -> Iterator[Path]:
56
+ """Render the charts of ``targets``; yield each file as it is written.
57
+
58
+ ``until`` ends the window and ``now`` dates the footers. Every store
59
+ is read and checked before the first chart is drawn, so a failure
60
+ there, raised as the exit `fail` builds, leaves no partial output.
61
+ """
62
+ # Imported here so other commands start without loading matplotlib.
63
+ from github_statistics.render.charts import render_target
64
+ from github_statistics.series import build_series
65
+
66
+ config = resolution.config
67
+ root = Path(config.cache.directory or default_cache_dir())
68
+ stores = {
69
+ target.owner: store_path(root, API_HOST, target.owner) for target in targets
70
+ }
71
+ for owner, path in stores.items():
72
+ if not path.is_file():
73
+ raise fail(f"no store for {owner} at {path}: run `collect` first")
74
+ built = []
75
+ for target in targets:
76
+ path = stores[target.owner]
77
+ try:
78
+ with ReadOnlyStore(path) as store:
79
+ series = build_series(
80
+ store,
81
+ config,
82
+ target,
83
+ until=until,
84
+ identities=resolution.identities_for(target),
85
+ )
86
+ dropped = _unselected(
87
+ target, store.scoped_between(series.days[0], series.days[-1])
88
+ )
89
+ except StaleStoreError:
90
+ raise fail(
91
+ f"the store at {path} has another schema version: run `collect` first"
92
+ ) from None
93
+ except sqlite3.DatabaseError as exc:
94
+ raise fail(f"cannot read the store at {path}: {exc}") from None
95
+ if dropped:
96
+ raise fail(
97
+ f"the store for {target.owner} holds {', '.join(dropped)} in the"
98
+ " window, outside the repository selection, and render cannot"
99
+ " leave it out: render without the selection, or `collect` the"
100
+ " selection into its own --cache-dir"
101
+ )
102
+ built.append((target, series))
103
+ for target, series in built:
104
+ try:
105
+ charts = render_target(
106
+ series, config, target, Path(config.output.directory), now=now
107
+ )
108
+ except ValueError as exc:
109
+ raise fail(str(exc)) from None
110
+ for chart in charts:
111
+ yield from chart.paths
112
+
113
+
114
+ @shared_options
115
+ def render(options: SharedOptions) -> None:
116
+ """Render the charts of every target from the store; needs no token."""
117
+ try:
118
+ resolution = options.resolve()
119
+ except ConfigError as exc:
120
+ raise fail(str(exc)) from None
121
+ now = datetime.now(UTC)
122
+ until = options.until or now.date() - timedelta(days=1)
123
+ for written in render_targets(
124
+ resolution, resolution.config.targets, until=until, now=now
125
+ ):
126
+ typer.echo(str(written))
@@ -0,0 +1,137 @@
1
+ # SPDX-License-Identifier: Apache-2.0
2
+ # SPDX-FileCopyrightText: 2026 The Linux Foundation
3
+ """The ``run`` command: every stage for every target, as the action runs it (design §4.2, §9.1).
4
+
5
+ For each target in turn ``run`` clears the target's ``img/`` and
6
+ ``data/`` directories, then collects, renders, exports and reads what
7
+ the target's pages show; the pages and the landing page are written
8
+ once, after every target. A spent budget is not a failure: rendering
9
+ and the site go on, and the charts show the gaps. A rejected token or
10
+ an invalid configuration stops the run before anything is rendered.
11
+ Exit codes are those of ``collect``: 1 for an invalid configuration or
12
+ a failed stage, 2 with ``--strict`` once the site is written if a
13
+ repository was unreadable, and 3 for a rejected token.
14
+ """
15
+
16
+ from __future__ import annotations
17
+
18
+ import shutil
19
+ import sqlite3
20
+ from collections.abc import Iterable
21
+ from datetime import UTC, datetime, timedelta
22
+ from pathlib import Path
23
+
24
+ import typer
25
+
26
+ from github_statistics.config import ConfigError, Resolution, Target, default_cache_dir
27
+ from github_statistics.store import path_component, store_path
28
+
29
+ from .collect import STRICT_EXIT, collect_outputs, collect_target, report
30
+ from .common import (
31
+ API_HOST,
32
+ ReadOnlyStore,
33
+ StaleStoreError,
34
+ append_summary,
35
+ fail,
36
+ write_outputs,
37
+ )
38
+ from .doctor import BOT_KEYS
39
+ from .export import DATA_DIR, export_targets
40
+ from .options import SharedOptions, shared_options
41
+ from .render import render_targets
42
+ from .site import site_targets, write_site
43
+
44
+ IMAGES_DIR = "img"
45
+
46
+
47
+ def clear_target_output(output_dir: Path, owner: str) -> None:
48
+ """Remove ``owner``'s ``img/`` and ``data/`` under ``output_dir``, and nothing else.
49
+
50
+ A file left by an earlier run, such as the export of a repository
51
+ since purged, must not reach the published site. An owner directory
52
+ that is a symbolic link is refused: clearing through it would
53
+ delete, and the stages would then write, outside ``output_dir``.
54
+ """
55
+ owner_dir = output_dir / path_component(owner, "owner")
56
+ if owner_dir.is_symlink():
57
+ raise fail(f"refusing to clear {owner_dir}: it is a symbolic link")
58
+ for name in (IMAGES_DIR, DATA_DIR):
59
+ path = owner_dir / name
60
+ if path.is_symlink() or path.is_file():
61
+ path.unlink()
62
+ elif path.is_dir():
63
+ shutil.rmtree(path)
64
+
65
+
66
+ def unclassified(resolution: Resolution, target: Target) -> list[str]:
67
+ """The stored bots of ``target`` named in no identity list; none if unreadable."""
68
+ from github_statistics.series import unclassified_bots
69
+
70
+ config = resolution.config
71
+ root = Path(config.cache.directory or default_cache_dir())
72
+ try:
73
+ with ReadOnlyStore(store_path(root, API_HOST, target.owner)) as store:
74
+ return unclassified_bots(store, resolution.identities_for(target))
75
+ except (StaleStoreError, sqlite3.DatabaseError):
76
+ return []
77
+
78
+
79
+ def _echo(paths: Iterable[Path]) -> None:
80
+ """Print each of ``paths``, one per line."""
81
+ for path in paths:
82
+ typer.echo(str(path))
83
+
84
+
85
+ @shared_options
86
+ def run(
87
+ options: SharedOptions,
88
+ refresh: bool = typer.Option(
89
+ False, "--refresh", help="Ignore watermarks and coverage; re-read the window."
90
+ ),
91
+ strict: bool = typer.Option(
92
+ False, "--strict", help="Exit 2 if any repository was unreadable."
93
+ ),
94
+ ) -> None:
95
+ """Collect, render, export and build the site for every target."""
96
+ try:
97
+ resolution = options.resolve()
98
+ except ConfigError as exc:
99
+ raise fail(str(exc)) from None
100
+ config = resolution.config
101
+ now = datetime.now(UTC)
102
+ until = options.until or now.date() - timedelta(days=1)
103
+ output_dir = Path(config.output.directory)
104
+ results = []
105
+ sites = []
106
+ bots: set[str] = set()
107
+ for target in config.targets:
108
+ clear_target_output(output_dir, target.owner)
109
+ results.append(
110
+ collect_target(
111
+ resolution, target, now=now, until=options.until, refresh=refresh
112
+ )
113
+ )
114
+ _echo(render_targets(resolution, [target], until=until, now=now))
115
+ _echo(export_targets(resolution, [target], until=until, generated=now.date()))
116
+ sites += site_targets(resolution, [target], until=until)
117
+ bots.update(unclassified(resolution, target))
118
+ _echo(write_site(sites, config, now=now))
119
+
120
+ found = sorted(bots)
121
+ summary = report(results)
122
+ summary += f"### Site\n\nWritten to `{output_dir}`.\n\n"
123
+ if found:
124
+ summary += f"Unclassified bots: {', '.join(found)}; add each to {BOT_KEYS}.\n"
125
+ append_summary(summary)
126
+ write_outputs(
127
+ {
128
+ "site_dir": str(output_dir),
129
+ **collect_outputs(results),
130
+ "unclassified_bots": ",".join(found),
131
+ },
132
+ heredoc=True,
133
+ )
134
+ for login in found:
135
+ typer.echo(f"warning: unclassified bot {login}: add it to {BOT_KEYS}", err=True)
136
+ if strict and any(result.unreadable for result in results):
137
+ raise fail("some repositories were unreadable (--strict)", STRICT_EXIT)
@@ -0,0 +1,96 @@
1
+ # SPDX-License-Identifier: Apache-2.0
2
+ # SPDX-FileCopyrightText: 2026 The Linux Foundation
3
+ """The ``scope`` command: print the resolved public repositories (design §4.2, §9.2).
4
+
5
+ Standard output carries repository names alone, so a workflow can hand
6
+ them to the token action; every warning and the dropped list go to
7
+ standard error. An empty scope prints nothing and exits 0: the caller
8
+ checks for empty output, since an empty repository list given to the
9
+ token action would grant the whole installation. A repository whose
10
+ read failed leaves the scope incomplete, so the command then prints no
11
+ names and exits 1. The command never touches the store.
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ import asyncio
17
+ import json
18
+ from enum import StrEnum
19
+
20
+ import httpx
21
+ import typer
22
+
23
+ from github_statistics.client import Budget, ClientError, Transport
24
+ from github_statistics.config import ConfigError, resolve_token
25
+ from github_statistics.scope import ResolvedScope, resolve_scope
26
+
27
+ from .common import fail
28
+ from .options import SharedOptions, shared_options
29
+
30
+
31
+ class Format(StrEnum):
32
+ """How ``scope`` prints the repository names."""
33
+
34
+ LINES = "lines"
35
+ CSV = "csv"
36
+ JSON = "json"
37
+
38
+
39
+ def _render(names: list[str], output: Format) -> str:
40
+ """``names`` in ``output`` format."""
41
+ if output is Format.CSV:
42
+ return ",".join(names)
43
+ if output is Format.JSON:
44
+ return json.dumps(names)
45
+ return "\n".join(names)
46
+
47
+
48
+ @shared_options
49
+ def scope(
50
+ options: SharedOptions,
51
+ output: Format = typer.Option(
52
+ Format.LINES, "--format", help="Output format for the repository names."
53
+ ),
54
+ ) -> None:
55
+ """Print the public repositories one owner resolves to, one name per line."""
56
+ try:
57
+ config = options.resolve().config
58
+ except ConfigError as exc:
59
+ raise fail(str(exc)) from None
60
+ if len(config.targets) != 1:
61
+ raise fail(
62
+ "scope resolves one owner at a time; select one with --org or --repo"
63
+ )
64
+ [target] = config.targets
65
+
66
+ limits = config.budget
67
+ budget = Budget(
68
+ rest=limits.rest, graphql_points=limits.graphql_points, reserve=limits.reserve
69
+ )
70
+
71
+ async def run() -> ResolvedScope:
72
+ async with Transport(resolve_token(target), budget=budget) as transport:
73
+ await transport.seed_budget()
74
+ return await resolve_scope(transport, target)
75
+
76
+ try:
77
+ resolved = asyncio.run(run())
78
+ except (ClientError, httpx.HTTPError) as exc:
79
+ raise fail(f"cannot resolve the scope of {target.owner}: {exc}") from None
80
+
81
+ for drop in resolved.dropped:
82
+ typer.echo(f"dropped {resolved.owner}/{drop.name}: {drop.reason}", err=True)
83
+ for name in resolved.unresolved:
84
+ typer.echo(f"warning: could not read {resolved.owner}/{name}", err=True)
85
+ if resolved.unresolved:
86
+ raise fail(
87
+ f"the scope of {resolved.owner} is incomplete:"
88
+ f" {len(resolved.unresolved)} repositories could not be read"
89
+ )
90
+ names = [repository.name for repository in resolved.repositories]
91
+ if not names:
92
+ typer.echo(
93
+ f"warning: no public repositories in scope for {resolved.owner}", err=True
94
+ )
95
+ return
96
+ typer.echo(_render(names, output))
@@ -0,0 +1,150 @@
1
+ # SPDX-License-Identifier: Apache-2.0
2
+ # SPDX-FileCopyrightText: 2026 The Linux Foundation
3
+ """The ``site`` command: the static site from the store (design §4.2, §8.5).
4
+
5
+ Needs no token and sends no request. Each store opens read-only, as for
6
+ ``export``; a missing or stale store fails naming ``collect``, and a
7
+ repository selection narrower than the store fails as it does for
8
+ ``render``. Every store is read before the first page is written. The
9
+ pages link to the charts ``render`` wrote and the files ``export``
10
+ wrote; this command writes neither. Standard output lists the files
11
+ written, one per line.
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ import sqlite3
17
+ from collections.abc import Sequence
18
+ from datetime import UTC, date, datetime, timedelta
19
+ from pathlib import Path
20
+ from typing import TYPE_CHECKING
21
+
22
+ import typer
23
+
24
+ from github_statistics.config import (
25
+ Config,
26
+ ConfigError,
27
+ Resolution,
28
+ ResolvedIdentities,
29
+ Target,
30
+ default_cache_dir,
31
+ )
32
+ from github_statistics.store import Store, store_path
33
+
34
+ from .common import API_HOST, ReadOnlyStore, StaleStoreError, fail
35
+ from .options import SharedOptions, shared_options
36
+ from .render import _unselected
37
+
38
+ if TYPE_CHECKING:
39
+ from github_statistics.site import SiteTarget
40
+
41
+
42
+ def _merged(
43
+ store: Store,
44
+ owner: str,
45
+ days: tuple[date, ...],
46
+ identities: ResolvedIdentities,
47
+ ) -> int:
48
+ """Pull requests merged over ``days``, classed as the daily series classes them.
49
+
50
+ A deleted author counts, as it does in the series; an ignored login
51
+ does not.
52
+ """
53
+ from github_statistics.series.actors import classify, public_members
54
+
55
+ members = public_members(store, identities, owner=owner)
56
+ return sum(
57
+ count
58
+ for login, account_type, count in store.item_actor_counts(
59
+ "pr", "merged_at", days[0], days[-1]
60
+ )
61
+ if classify(login, account_type, identities, members) is not None
62
+ )
63
+
64
+
65
+ def site_targets(
66
+ resolution: Resolution, targets: Sequence[Target], *, until: date
67
+ ) -> list[SiteTarget]:
68
+ """Read what the pages of ``targets`` show from their stores, up to ``until``.
69
+
70
+ Every store is read before any page is written; a missing, stale or
71
+ unreadable store, or a selection narrower than the store, raises the
72
+ exit `fail` builds.
73
+ """
74
+ # Imported here so other commands start without loading matplotlib.
75
+ from github_statistics.series import (
76
+ build_leaderboard,
77
+ build_repositories,
78
+ build_series,
79
+ )
80
+ from github_statistics.site import SiteTarget
81
+
82
+ config = resolution.config
83
+ root = Path(config.cache.directory or default_cache_dir())
84
+ stores = {
85
+ target.owner: store_path(root, API_HOST, target.owner) for target in targets
86
+ }
87
+ for owner, path in stores.items():
88
+ if not path.is_file():
89
+ raise fail(f"no store for {owner} at {path}: run `collect` first")
90
+ built = []
91
+ for target in targets:
92
+ path = stores[target.owner]
93
+ identities = resolution.identities_for(target)
94
+ try:
95
+ with ReadOnlyStore(path) as store:
96
+ series = build_series(
97
+ store, config, target, until=until, identities=identities
98
+ )
99
+ contributors = build_leaderboard(
100
+ store, config, target, until=until, identities=identities
101
+ )
102
+ repositories = build_repositories(
103
+ store, config, target, until=until, identities=identities
104
+ )
105
+ merged = _merged(store, target.owner, series.days, identities)
106
+ except sqlite3.DatabaseError as exc:
107
+ raise fail(f"cannot read the store at {path}: {exc}") from None
108
+ except StaleStoreError:
109
+ raise fail(f"the store at {path} is stale: run `collect` first") from None
110
+ dropped = _unselected(target, [row.repo for row in repositories])
111
+ if dropped:
112
+ raise fail(
113
+ f"the store for {target.owner} holds {', '.join(dropped)} in the"
114
+ " window, outside the repository selection, and site cannot"
115
+ " leave it out: build without the selection, or `collect` the"
116
+ " selection into its own --cache-dir"
117
+ )
118
+ built.append(
119
+ SiteTarget(target, series, contributors, repositories, merged, identities)
120
+ )
121
+ return built
122
+
123
+
124
+ def write_site(
125
+ sites: Sequence[SiteTarget], config: Config, *, now: datetime
126
+ ) -> list[Path]:
127
+ """Write the pages of ``sites`` and the landing page; the files written."""
128
+ from github_statistics.site import build_site
129
+
130
+ return build_site(sites, config, Path(config.output.directory), now=now)
131
+
132
+
133
+ @shared_options
134
+ def site(options: SharedOptions) -> None:
135
+ """Write the HTML pages of every target from the store; needs no token.
136
+
137
+ The output directory must hold the charts and data of the same run,
138
+ from `render` and `export`; site links them and does not check their
139
+ freshness.
140
+ """
141
+ try:
142
+ resolution = options.resolve()
143
+ except ConfigError as exc:
144
+ raise fail(str(exc)) from None
145
+ config = resolution.config
146
+ now = datetime.now(UTC)
147
+ until = options.until or now.date() - timedelta(days=1)
148
+ built = site_targets(resolution, config.targets, until=until)
149
+ for written in write_site(built, config, now=now):
150
+ typer.echo(str(written))
@@ -0,0 +1,40 @@
1
+ # SPDX-License-Identifier: Apache-2.0
2
+ # SPDX-FileCopyrightText: 2026 The Linux Foundation
3
+ """The GitHub client every collector uses (design §4.1, §6.5)."""
4
+
5
+ from __future__ import annotations
6
+
7
+ from .accounting import RequestStats
8
+ from .budget import Budget
9
+ from .errors import (
10
+ AuthError,
11
+ BudgetExhaustedError,
12
+ ClientError,
13
+ ForeignHostError,
14
+ GraphQLError,
15
+ TransportError,
16
+ )
17
+ from .graphql import Batched, batched, graphql
18
+ from .paging import Conditional, get_conditional, get_paged
19
+ from .policy import graphql_url, parse_retry_after
20
+ from .transport import Transport
21
+
22
+ __all__ = [
23
+ "AuthError",
24
+ "Batched",
25
+ "Budget",
26
+ "BudgetExhaustedError",
27
+ "ClientError",
28
+ "Conditional",
29
+ "ForeignHostError",
30
+ "GraphQLError",
31
+ "RequestStats",
32
+ "Transport",
33
+ "TransportError",
34
+ "batched",
35
+ "get_conditional",
36
+ "get_paged",
37
+ "graphql",
38
+ "graphql_url",
39
+ "parse_retry_after",
40
+ ]
@@ -0,0 +1,99 @@
1
+ # SPDX-License-Identifier: Apache-2.0
2
+ # SPDX-FileCopyrightText: 2026 The Linux Foundation
3
+ """What one transport's requests cost: its stats and its budget charges."""
4
+
5
+ from __future__ import annotations
6
+
7
+ from collections import Counter
8
+ from dataclasses import dataclass, field
9
+ from typing import Any
10
+
11
+ import httpx
12
+
13
+ from .budget import Budget
14
+ from .errors import BudgetExhaustedError, ClientError
15
+ from .policy import int_header
16
+
17
+
18
+ @dataclass
19
+ class RequestStats:
20
+ """What a transport has done so far in a run."""
21
+
22
+ requests: int = 0
23
+ retries: Counter[str] = field(default_factory=Counter)
24
+ not_modified: int = 0
25
+ bytes_received: int = 0
26
+ rate_limit_remaining: int | None = None
27
+ rate_limit_reset: int | None = None
28
+ graphql_cost: int = 0
29
+ graphql_remaining: int | None = None
30
+
31
+
32
+ @dataclass
33
+ class Ledger:
34
+ """One transport's stats and its ``Budget``, if any.
35
+
36
+ ``authenticated`` says whether the transport sends a token, which
37
+ alone makes a ``304`` free.
38
+ """
39
+
40
+ budget: Budget | None
41
+ authenticated: bool
42
+ stats: RequestStats = field(default_factory=RequestStats)
43
+
44
+ def reserve(self, label: str, *, rest: bool) -> None:
45
+ """Take one REST request for an attempt before it is sent.
46
+
47
+ Raises ``BudgetExhaustedError`` when none is left.
48
+ """
49
+ if rest and self.budget is not None and not self.budget.try_spend_rest():
50
+ raise BudgetExhaustedError(f"no REST budget left for {label}")
51
+
52
+ def refund(self, *, rest: bool) -> None:
53
+ """Give back an attempt's REST request, for one that never left."""
54
+ if rest and self.budget is not None:
55
+ self.budget.refund_rest()
56
+
57
+ def record(self, response: httpx.Response, *, graphql: bool, rest: bool) -> None:
58
+ """Account for ``response`` in the stats and the budget.
59
+
60
+ Every REST response's core quota headers reach the budget, a
61
+ ``304`` included. GitHub waives the charge for an authenticated
62
+ ``304`` alone, so an anonymous one stays charged.
63
+ """
64
+ stats = self.stats
65
+ stats.bytes_received += len(response.content)
66
+ remaining = int_header(response, "x-ratelimit-remaining")
67
+ reset = int_header(response, "x-ratelimit-reset")
68
+ if remaining is not None:
69
+ stats.rate_limit_remaining = remaining
70
+ if reset is not None:
71
+ stats.rate_limit_reset = reset
72
+ if response.status_code == 304:
73
+ stats.not_modified += 1
74
+ budget = self.budget
75
+ if budget is None or graphql:
76
+ return
77
+ core = response.headers.get("x-ratelimit-resource", "core") == "core"
78
+ if core and remaining is not None:
79
+ budget.observe(remaining, reset)
80
+ if rest and response.status_code == 304 and self.authenticated:
81
+ budget.refund_rest()
82
+
83
+ def seed(self, response: httpx.Response, payload: Any) -> None:
84
+ """Observe the core quota in a ``GET /rate_limit`` ``payload``.
85
+
86
+ Raises ``ClientError`` when neither the payload nor the
87
+ response's own core-resource headers carry a core count.
88
+ """
89
+ if self.budget is None:
90
+ return
91
+ resources = payload.get("resources") if isinstance(payload, dict) else None
92
+ core = resources.get("core") if isinstance(resources, dict) else None
93
+ remaining = core.get("remaining") if isinstance(core, dict) else None
94
+ reset = core.get("reset") if isinstance(core, dict) else None
95
+ header_core = response.headers.get("x-ratelimit-resource", "core") == "core"
96
+ if isinstance(remaining, int):
97
+ self.budget.observe(remaining, reset if isinstance(reset, int) else None)
98
+ elif not header_core or int_header(response, "x-ratelimit-remaining") is None:
99
+ raise ClientError("GET /rate_limit returned no core rate-limit count")