diff --git a/.github/workflows/email-report.yml b/.github/workflows/email-report.yml index 02511ef..8d94e32 100644 --- a/.github/workflows/email-report.yml +++ b/.github/workflows/email-report.yml @@ -69,9 +69,9 @@ jobs: - uses: actions/setup-python@v7 with: python-version: '3.12' - # Editable install of this repo's own package. pip does not read uv.lock; - # the core package currently declares no runtime dependencies, so nothing - # else is resolved here. + # Editable install of this repo's own package. It declares no runtime + # dependencies, but pip still resolves the setuptools>=77.0.3 build + # backend in an isolated env (not from uv.lock). - run: pip install -e . # NOSONAR - name: Send email report env: diff --git a/.github/workflows/email-report.yml.template b/.github/workflows/email-report.yml.template index 8f46727..aca3072 100644 --- a/.github/workflows/email-report.yml.template +++ b/.github/workflows/email-report.yml.template @@ -69,7 +69,10 @@ jobs: - uses: actions/setup-python@v7 with: python-version: '3.12' - - run: pip install -e . + # Editable install of this repo's own package. It declares no runtime + # dependencies, but pip still resolves the setuptools>=77.0.3 build + # backend in an isolated env (not from uv.lock). + - run: pip install -e . # NOSONAR - name: Send email report env: GH_USAGE_TOKEN: ${{ secrets.GH_USAGE_TOKEN }} diff --git a/CHANGELOG.md b/CHANGELOG.md index 967d36a..6655ee3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -20,6 +20,7 @@ This project follows the structure from Keep a Changelog and intends to use Sema ### Added +- **Measured REST API usage in reports** ([plan](docs/superpowers/plans/archived/2026-11-09-api-call-tracking.md)): email quota blocks, terminal output, CSV/XLSX/PDF exports, and TUI detail rows report measured-vs-estimated GitHub REST API requests — scope requests vs the pre-fetch estimate, total requests issued (retries excluded), core quota remaining at report start, the core rate limit with a docs link, a per-resource breakdown, and the live/cached source (JSON `api_estimate` carries the same measured data; the 5,000/hour fallback and documentation link are added by the rendered sections only). Report cache version bumped to 4 (stale v3 snapshots rejected). - **Known-vulnerable Actions check:** new `vulnerable-actions` job in the `Security` workflow runs zizmor's `known-vulnerable-actions` audit on every PR, push to `main`, and the weekly schedule, failing on any action reference with a GitHub security advisory. Covers SHA-pinned actions (e.g. `gitleaks-action`), which Dependabot alerts never flag; fails loudly if the audit itself errors or `GH_TOKEN` is empty. - **Coverage, complexity, and module-size gates:** `scripts/coverage-check` runs the unittest suite under `coverage` (scoped to `src/github_usage`). Overall src coverage must stay ≥ `COVERAGE_TOTAL_MIN` (default 75; current ~76%). Any **new** `src` file (not in the committed tree) must meet `COVERAGE_FILE_MIN` (default 82%) so coverage cannot erode one file at a time; existing files are protected by the overall gate only. `scripts/check-complexity` fails if the worst cyclomatic complexity exceeds `MAX_CC` (default 28; current worst) and warns at `WARN_LINES`=575 / blocks at `BLOCK_LINES`=650 for module size (current largest 562). Both scripts are wired into `scripts/check`, added as pre-push hooks in `.pre-commit-config.yaml`, and coverage runs as its own `coverage` job in `ci.yml`. `coverage` and `radon` added to the `dev` extra; `uv.lock` regenerated. - **Private-repo top consumers** ([plan](docs/superpowers/plans/archived/2026-07-31-private-top-consumers.md)): local full report (terminal + TUI), email text/HTML, and JSON exports gain private-only top lists for Actions minutes and billed storage alongside existing overall rankings; overall top-by-storage (billed avg MB) and artifact-scan private lists where they add signal. Shared `repo_consumers.py` helper with `private_list_is_redundant` guards; report cache version bumped to 3. HTML table helpers extracted to `_email_report_html_tables.py`. diff --git a/TO_DO.md b/TO_DO.md index fa05a35..551fa4a 100644 --- a/TO_DO.md +++ b/TO_DO.md @@ -29,9 +29,9 @@ - [ ] Refactor `src/github_usage/setup_config.py` (507 lines, over the 500-line limit per `scripts/check-sizes`). Extract a focused submodule — e.g. profile schema/loading (`load_report_profiles`, `find_profile`, `ensure_profiles`, `_default_profile`) and/or the TOML writer helpers (`_emit_*_block`, `write_config`) — to bring the file back under the threshold. Also watch `setup_wizard.py` (461 lines) and the `_manage_profiles()`/`_run_email_report()` functions, which are approaching their limits. - [ ] Rename internal `legacy_*` modules/symbols to “local full report” naming (`legacy_report_data` → e.g. `local_report_data`, cache `kind="legacy"`, CLI/TUI internals, tests). User-facing copy already says “local full report”; this is the code rename. Keep a thin `legacy` compatibility shim if external imports still need it. +- [ ] Extract the remaining API-usage tracking orchestration from the report builders (`report_data.py` 487 lines, `legacy_report_data.py` 395 lines — both at/over the early-extraction threshold). Keep the merge math in `report_api_usage.py`; move section-fetch orchestration (`_fetch_sections`, `_fetch_legacy_billing_sections`) into a focused submodule so the builders stay thin. Flagged in review on PR #39; deferred to keep that PR's diff small. - [ ] Add tests to raise overall src coverage from the current ~76% to 80%. Update `scripts/coverage-check` default from `COVERAGE_TOTAL_MIN=75` to `80` once achieved. -- [ ] Port the manual `pip install -e .` comment + `# NOSONAR` in `.github/workflows/email-report.yml` into `email-report.yml.template` so the next setup regeneration does not silently drop the Sonar suppression. ## Configuration & Setup diff --git a/docs/email-reports.md b/docs/email-reports.md index e555bce..f9457a4 100644 --- a/docs/email-reports.md +++ b/docs/email-reports.md @@ -135,7 +135,7 @@ The email command supports the options below. Run `./start.sh email-report --hel - Missing GitHub `user` scope: billing endpoints may return 404. Fix GitHub CLI auth with `gh auth refresh -h github.com -s user`, or use a PAT with the `user` scope. - GitHub Actions token confusion: use `GH_USAGE_TOKEN`, not the automatic `GITHUB_TOKEN`. - Resend domain unverified: set `RESEND_FROM` to an address on a verified Resend domain. -- Rate limiting: reduce frequency, lower `--max-repos`, avoid repo-level options, or use skip flags. +- Rate limiting: reduce frequency, lower `--max-repos`, avoid repo-level options, or use skip flags. The report's REST API Usage section shows how many requests each run issued — on a cache hit it shows the request count from the original fetch, since the current run issued none; see [Reports and exports](reports.md). - Consumer breakdown truncation: increase `--max-repos` cautiously. - Artifact storage request cost: `--include-artifact-storage` can add roughly one REST API request per scanned repository. - Release asset inventory: `--include-release-assets` can add roughly one REST API request per scanned repository and requires explicit confirmation. diff --git a/docs/reports.md b/docs/reports.md index 897b9f6..c8be465 100644 --- a/docs/reports.md +++ b/docs/reports.md @@ -8,6 +8,8 @@ After [authenticating](setup.md#authentication), run a local full report with `. `--include-consumers`, `--include-artifact-storage`, and `--include-release-assets` add repo-level API calls. They consume GitHub REST API request quota, not Actions minutes, Actions storage, Copilot requests, Git LFS quota, or billable GitHub usage. Use monthly schedules and conservative `--max-repos` values for accounts with many repositories. +Every report also measures its own REST API footprint. Email quota blocks, terminal output, CSV/XLSX/PDF exports, and TUI detail rows carry a **REST API Usage** section: measured requests in the estimate scope vs the pre-fetch estimate, total requests issued (retries excluded), core quota remaining at report start, the core rate limit (live limit when available, else GitHub's documented 5,000/hour) with a link to [GitHub's rate-limit docs](https://docs.github.com/en/rest/using-the-rest-api/rate-limits-for-the-rest-api), a per-resource breakdown, and the source (live fetch, or cached report with the original-fetch total). The JSON `api_estimate` object carries the same measured data, including the live `core_limit` when the snapshot succeeded; the 5,000/hour fallback and the documentation link are added by the rendered sections only. Counts are logical requests issued, not raw HTTP attempts — retries are excluded. + With `--include-consumers` (local full report and email), the **repo consumers** sections rank repositories by Actions usage alongside the existing combined top-by-minutes and top-by-cost lists: - **Overall top-by-storage** — billed Actions storage ranked by average MB (`storage_avg_mb` from the billing API). @@ -62,7 +64,10 @@ exporting). Export redaction is partial; see [Privacy](#privacy) before sharing - **CSV** writes a UTF-8 BOM at the start of the file for Excel-on-Windows compatibility. - **JSON** preserves the full `ReportData` dict, including the `api_estimate` - metadata. Datetime values are emitted as ISO-8601 strings. + metadata (measured `actual_requests` / `total_requests`, + `actual_requests_by_resource`, `estimate_variance`, `estimate_scope` when + the window is explicit, `from_cache`). Datetime values are emitted as + ISO-8601 strings. - **XLSX** uses one sheet per major report section. Sheet names are truncated to 31 characters (Excel limit). Values starting with `=`, `+`, `-`, or `@` are prefixed with a single quote to prevent Excel formula injection. diff --git a/docs/superpowers/plans/2026-11-09-api-call-tracking.md b/docs/superpowers/plans/archived/2026-11-09-api-call-tracking.md similarity index 74% rename from docs/superpowers/plans/2026-11-09-api-call-tracking.md rename to docs/superpowers/plans/archived/2026-11-09-api-call-tracking.md index 3c8df25..20cb159 100644 --- a/docs/superpowers/plans/2026-11-09-api-call-tracking.md +++ b/docs/superpowers/plans/archived/2026-11-09-api-call-tracking.md @@ -1,10 +1,34 @@ -> **Status:** IN PROGRESS +> **Status:** COMPLETE > Line numbers cited below are accurate as of 2026-11-09; relocate by anchor (function / section title / dict key) if they drift. > > **Terminology:** user-facing name is **local full report** (CLI/TUI). Code modules still use `legacy_*` until the rename tracked in `TO_DO.md`. > -> **Implementation log:** (none yet) +> **Implementation log:** Chunk 1 complete 2026-11-11 — `GitHubAPI` request +> counting (`request_count`, `request_log`, ordered resource buckets) plus +> `get_request_stats()` and unit tests; reviewed APPROVE with minor findings +> folded in (structural sum==total, segment-based actions match, TypedDicts, +> dense zeroed buckets, normalized-path/params/404 tests). Chunk 2 complete +> 2026-11-11 — `report_api_usage.py` shared lines/rows formatters with scope +> labels, rate-limit reference line, and cache-hit message; 9 unit tests at +> 100% file coverage. Chunk 3 complete 2026-11-11 — builder merge with +> per-getter tracking, caller-passed legacy baselines with listing carve-out, +> `annotate_cache_hit` at all three cache sites, `CACHE_VERSION` 4, and +> CountingFakeAPI + builder/helper/cache-hit tests (831 tests green). +> Chunk-3 review (deepseek, APPROVE, no blockers): most findings were already +> satisfied by the implementation (caller-baseline and session tests, fallback +> `other`-bucket, extracted `_merge_legacy_api_estimate`, sorted buckets, +> multi-page `page_counts`, GUI test placement); applied the remainder — +> fallback non-dict/count-combined tests, section-level abort coverage, +> redaction assertions, `_track_repo_calls`/`deltas` typing, legacy docstring. +> Chunk 4 complete 2026-11-11 — email text/HTML quota blocks, legacy terminal +> renderer, CSV/XLSX/PDF sections, GUI detail rows; 15 new tests; deepseek +> APPROVE with follow-ups applied. Grok pre-PR review (high, plan mode): +> REQUEST CHANGES with one major (PDF label-column overprint — fixed with +> label/value split rows) and one minor (static rate-limit list docs link — +> fixed); committed as follow-up. Docs complete 2026-11-11 — +> `reports.md`, `email-reports.md`, CHANGELOG `Added` entry, full +> `scripts/check` green; plan archived. # Track GitHub REST API Calls and Report Usage @@ -163,8 +187,9 @@ Matching windows (baseline capture points): captured before initialization (a fresh-client zero snapshot is equivalent), never the entry default, preserving comparable counts with the CLI. When `baseline_stats` is None (direct builder use), the builder - snapshots at entry and records the narrower scope (`estimate_scope`) so - the variance stays honest. + snapshots at entry and records no scope, so renderers use the neutral + scope label instead of implying full-report coverage (the entry window is + narrower than the full estimate span). Carve `_limited_repos()` out of `actual_requests`: snapshot the counter around that call (`legacy_report_data.py:234`) and subtract those repository-listing page fetches from the delta — including from @@ -234,28 +259,38 @@ Add a shared formatter module `src/github_usage/report_api_usage.py` with one pure lines function plus a shared rows adapter, matching the existing `email_actions_table_rows` convention (`_email_report_common.py:30-39`): -- `api_usage_lines(estimate: dict) -> list[str]` -- `api_usage_rows(estimate: dict) -> list[tuple[str, str]]` derived from the +- `api_usage_lines(estimate: dict | None) -> list[str]` +- `api_usage_rows(estimate: dict | None) -> list[tuple[str, str]]` derived from the lines (label/value pairs for HTML tables, CSV, XLSX, PDF). Suggested content (compact): ``` REST API Usage -- Requests in estimate scope: 123 (estimated 120) -- Total requests this fetch: 130 +- Repo requests in estimate scope: 123 (estimated 120) +- Total requests this fetch (retries excluded): 130 - Core quota remaining before: 4,877 / 5,000 -- Core rate limit: 5,000 requests/hour (authenticated) — https://docs.github.com/en/rest/using-the-rest-api/rate-limits-for-the-rest-api -- By resource (estimate scope): billing 20, repos 1, actions 100, rate_limit 1, other 1 +- Core rate limit: 5,000 requests/hour (authenticated) - https://docs.github.com/en/rest/using-the-rest-api/rate-limits-for-the-rest-api +- By resource (estimate scope): actions 100, billing 20, repos 1 - Source: live fetch ``` -The scope label comes from `estimate_scope`: email renderers qualify it as -repo-level scope (`Repo-level requests in estimate scope:`), legacy renderers -as account-level-inclusive scope. +The scope label comes from `estimate_scope`: email renderers show +`Repo requests in estimate scope:`, legacy renderers show +`All requests in estimate scope:`, and unknown scopes fall back to the +neutral `Requests in estimate scope:`. Scope strings live as +`SCOPE_REPO_SECTIONS` / `SCOPE_FULL_REPORT` constants in +`report_api_usage.py` so builders import them instead of re-typing. +Formatters return no lines when the estimate carries no measurement keys, +zero-count buckets are omitted from the breakdown, and all strings are +ASCII-only (the PDF writer uses core Helvetica, which has no em dash). On a cache hit: `- Source: cached report (0 new API requests; 130 total during the original fetch)`. +Cached rendering keeps the original measurement on the scope line; only the +total line is relabeled. (Recorded 2026-11-11: do not zero the scope line — +chunk 4 must preserve this.) + Surface-by-surface: - **Email text** (`email_report_text.py`): do NOT add a new @@ -408,19 +443,69 @@ which already lists static rate-limit numbers, to include the same docs link. ## Task breakdown -- [ ] Add `GitHubAPI` request counting + `get_request_stats()`; unit tests. -- [ ] Add `report_api_usage.py` (lines + rows adapter); cover the new file's 82% +- [x] Add `GitHubAPI` request counting + `get_request_stats()`; unit tests. + **Done:** 2026-11-11 — counter, per-resource log, and stats merged in + `api.py`; 9 unit tests (incl. failure/transport, pagination, buckets); + reviewer minors applied (no functional deviations). +- [x] Add `report_api_usage.py` (lines + rows adapter); cover the new file's 82% coverage gate. -- [ ] Merge repo-level-delta actual usage into `api_estimate` in both builders - (email: per-getter snapshots around repo-level getters; legacy: - caller-passed `baseline_stats` full-snapshot subtraction incl. per-resource); - bump `CACHE_VERSION` (plus the test pin); add `annotate_cache_hit()` at all - three sites; tests. -- [ ] Extend the email text/HTML quota blocks; legacy terminal; CSV/XLSX/PDF; + **Done:** 2026-11-11 — shared `api_usage_lines`/`api_usage_rows` with scope + labels, quota/rate-limit/breakdown/source lines; 9 unit tests at 100% file + coverage. + **Review:** deepseek APPROVE with follow-ups applied — ASCII-only strings + (PDF-safe), absent-measurement gate returning no lines, zero-bucket filter, + cached total label, shared `SCOPE_*` constants, shorter PDF-safe labels. +- [x] Merge repo-level-delta actual usage into `api_estimate` in both builders + (email: per-getter snapshots around repo-level getters, using the shared + `SCOPE_*` constants for `estimate_scope`; legacy: caller-passed + `baseline_stats` full-snapshot subtraction incl. per-resource, minus the + `_limited_repos` listing calls); bump `CACHE_VERSION` (plus the test pin); + add `annotate_cache_hit()` at all three sites; tests. + **Done:** 2026-11-11 — per-getter `_track_repo_calls` + `_sum_repo_deltas` + merge in both builders; legacy caller-passed `baseline_stats` with listing + carve-out and omitted scope on entry fallback; `annotate_cache_hit` at all + three cache sites; `CACHE_VERSION` 4 + pin update; CountingFakeAPI (incl. + multi-page listings) + builder/helper/cache-hit integration tests (incl. + caller-baseline, 2-page invariance, session coverage, section-failure + fallback). + **Review:** deepseek APPROVE with follow-ups folded in — `_api_request_stats` + fallback buckets unknowns under `other`; merge helpers consolidated in + `report_api_usage.py` (report_data.py stays under the 500-line budget); + non-dict snapshots tolerated; exact-bucket test assertions kept where they + pin the dense contract; legacy None-baseline omits (rather than invents) a + scope value. + **Review 2:** deepseek APPROVE (no blockers) with minors applied — caller- + baseline test proves pre-builder inclusion; `_merge_legacy_api_estimate` + extracted to `report_api_usage.py` (~163→~140-line builder); section-level + abort path tested with fallback re-run; `annotate_cache_hit` covered at all + three call sites via integration tests; `_track_repo_calls`/`deltas` typed; + monotonicity documented; GUI test module ordering fixed. +- [x] Extend the email text/HTML quota blocks; legacy terminal; CSV/XLSX/PDF; GUI legacy detail rows; add the rate-limit reference line + docs link; - tests. -- [ ] Docs (`docs/reports.md`, `docs/email-reports.md`), changelog, + tests. Chunk-4 decisions (locked): keep the cached scope line as the original + measurement (only the total line is relabeled); gate the extended quota + block on `notes or usage lines` so measured reports with zero notes still + render; label totals as requests-issued (retries excluded); HTML docs URL + stays plain text (matches text body; mail clients autolink); terminal keeps + both quota lines (usage block stays self-contained); PDF renders every entry + as a label line followed by its value line (fixed-width cells can't wrap). + **Review:** deepseek APPROVE with follow-ups applied — ruff-format fixes, + per-surface docs-link assertions, uniform PDF label/value split (no + overprint), shared "REST API Usage" naming, `_track_repo_calls` typing, + moved GUI cache test above the `__main__` guard. + **Pre-PR review (grok 4.7 high, plan mode):** REQUEST CHANGES with one + major (PDF 60 mm label column overprints the total-request counts — + fixed by rendering every API-usage entry as a label line followed by a + full-width value line, plus `add_section` full-width handling for + empty label/value rows) and one minor (static `render_what_else` + rate-limit list missing the docs link — fixed). Nits recorded as + follow-ups, not blockers. +- [x] Docs (`docs/reports.md`, `docs/email-reports.md`), changelog, `scripts/check`, and a final review. + **Done:** 2026-11-11 — REST API Usage section documented in `reports.md` + (JSON `api_estimate` fields enumerated), rate-limit troubleshooting pointer + in `email-reports.md`, CHANGELOG `Added` entry under `[Unreleased]`; + `scripts/check` and `scripts/docs-check` green. ## Related follow-ups (out of scope here) diff --git a/docs/superpowers/plans/2026-11-09-template-drift-pip-nosonar.md b/docs/superpowers/plans/archived/2026-11-09-template-drift-pip-nosonar.md similarity index 81% rename from docs/superpowers/plans/2026-11-09-template-drift-pip-nosonar.md rename to docs/superpowers/plans/archived/2026-11-09-template-drift-pip-nosonar.md index ea49bab..e077aa6 100644 --- a/docs/superpowers/plans/2026-11-09-template-drift-pip-nosonar.md +++ b/docs/superpowers/plans/archived/2026-11-09-template-drift-pip-nosonar.md @@ -1,10 +1,14 @@ -> **Status:** IN PROGRESS +> **Status:** COMPLETE > Line numbers cited below are accurate as of 2026-11-09; relocate by anchor (comment text / step name) if they drift. > > **Terminology:** user-facing name is **local full report** (CLI/TUI). Code modules still use `legacy_*` until the rename tracked in `TO_DO.md`. > -> **Implementation log:** (none yet) +> **Implementation log:** 2026-11-11 — corrected block applied to the template +> and the committed workflow identically; 3 pinning tests added +> (render assertion, block-agreement, render-vs-committed byte-parity); +> deepseek review APPROVE (no blockers/majors; stale Scope bullet fixed, +> test import hoisted, new test moved after the forecast group). # Port Manual pip-install Comment + NOSONAR into email-report Template @@ -69,7 +73,7 @@ complete (per repo rule, completed items are removed, not checked off). not the template file itself. - No change to `render_workflow()` — static text passes through; no new placeholder needed. -- No change to the committed `email-report.yml` — it already has the block. +- The corrected block also replaces the old wording in the committed `email-report.yml` (it already had a block, but with the overclaiming third line) so both files stay identical. - Verify there is no *other* committed-vs-template drift while here (last verified 2026-11-09: the pip-install block was the only delta). @@ -126,11 +130,19 @@ complete (per repo rule, completed items are removed, not checked off). ## Task breakdown -- [ ] Port the comment + `# NOSONAR` into `email-report.yml.template`. -- [ ] Add the `test_setup_workflow.py` render assertion and the +- [x] Port the comment + `# NOSONAR` into `email-report.yml.template`. + **Done:** 2026-11-11 — corrected 4-line block in the template; identical + block replaces the old wording in the committed workflow. +- [x] Add the `test_setup_workflow.py` render assertion and the `test_workflow_templates.py` parity assertion. -- [ ] Verify static parity via the updated unit tests (in-memory config + **Done:** 2026-11-11 — render assertion, block-agreement test, and + render-vs-committed byte-parity test (in-memory config, machine-independent). +- [x] Verify static parity via the updated unit tests (in-memory config matching the committed workflow's parameters, not the local gitignored config); run `scripts/check` and `scripts/docs-check`. -- [ ] Confirm SonarCloud check green on the PR; remove the `TO_DO.md` item; + **Done:** 2026-11-11 — byte-parity confirmed (3253 == 3253 bytes); tests, + typecheck, docs-check, and ruff (repo-pinned 0.9.6) green. +- [x] Confirm SonarCloud check green on the PR; remove the `TO_DO.md` item; archive this plan. + **Done:** 2026-11-11 — `TO_DO.md` item removed; plan archived in the same + change set. SonarCloud green to be confirmed on the PR. diff --git a/src/github_usage/api.py b/src/github_usage/api.py index e870959..8e80a92 100644 --- a/src/github_usage/api.py +++ b/src/github_usage/api.py @@ -4,12 +4,62 @@ import json import urllib.parse +from typing import TypedDict from . import __version__ + +class RequestStats(TypedDict): + """Measured API usage: total logical calls plus a per-resource breakdown.""" + + actual_requests: int + actual_requests_by_resource: dict[str, int] + + +class _RequestLogEntry(TypedDict): + """One counted logical API call; ``status`` is None when no response was observed.""" + + method: str + path: str + status: int | None + + # GitHub list endpoints that return {total_count, : [...]} instead of a bare array. _COLLECTION_KEYS = ("workflow_runs", "artifacts", "workflows") +# All stats resource buckets with zeroed counts. Billing paths live under +# ``/users/...`` and the repository listing lives under ``/user/repos``, +# so both are matched before the general ``/user`` prefix below. +_RESOURCE_BUCKETS = ("billing", "user", "rate_limit", "actions", "repos", "other") + + +def _loggable_path(url: str) -> str: + """Return the bare path for request logging (stats buckets match on paths). + + Any inline query string is stripped; the full URL is still transmitted. + """ + return url.split("?", 1)[0] + + +# Resource buckets for request stats, evaluated in order: billing paths start +# with ``/users/...`` so billing must be matched before the user prefix. +def _classify_request_path(path: str) -> str: + """Map a request path to a stats resource bucket.""" + if "/settings/billing/" in path: + return "billing" + if path == "/user/repos" or path.startswith("/user/repos/"): + return "repos" + if path == "/user" or path.startswith("/user/"): + return "user" + if path.startswith("/rate_limit"): + return "rate_limit" + if path.startswith("/repos/"): + parts = path.split("/") + if len(parts) > 4 and parts[4] == "actions": + return "actions" + return "repos" + return "other" + class GitHubAPI: def __init__(self, token, timeout=None, max_retries=None): @@ -20,6 +70,11 @@ def __init__(self, token, timeout=None, max_retries=None): self.max_retries = ( max_retries if max_retries is not None else http_retry.DEFAULT_MAX_RETRIES ) + # Request accounting for the API-usage report. Single-threaded use + # only: reports never share a client across threads (GUI workers each + # build their own client; see gui_backend.run_legacy_report_data). + self.request_count: int = 0 + self.request_log: list[_RequestLogEntry] = [] self.base = "https://api.github.com" self.headers = { "Accept": "application/vnd.github+json", @@ -28,10 +83,40 @@ def __init__(self, token, timeout=None, max_retries=None): "User-Agent": f"github-usage-report/{__version__} (+https://github.com/kgrizz-git/github-usage)", } + def _record_request_start(self, method: str, path: str) -> _RequestLogEntry: + """Count one logical API call and open its request-log entry. + + The entry's ``status`` is filled in once a response is observed; + ``None`` means no response was observed at this layer (transport + failure, or a retryable 5xx that exhausted retries). + """ + self.request_count += 1 + entry: _RequestLogEntry = {"method": method, "path": path, "status": None} + self.request_log.append(entry) + return entry + + def get_request_stats(self) -> RequestStats: + """Return actual request totals plus a per-resource breakdown. + + ``actual_requests`` is derived from the log so it cannot drift from + the breakdown. Only aggregates are exposed: ``request_log`` entries + (raw paths) never enter report data, since they would bypass the + export redaction layer. + """ + by_resource: dict[str, int] = dict.fromkeys(_RESOURCE_BUCKETS, 0) + for entry in self.request_log: + bucket = _classify_request_path(entry["path"]) + by_resource[bucket] = by_resource.get(bucket, 0) + 1 + return { + "actual_requests": len(self.request_log), + "actual_requests_by_resource": by_resource, + } + def request(self, method, path, params=None): url = path if not url.startswith("/"): url = "/" + url + entry = self._record_request_start(method, _loggable_path(url)) if params: query = urllib.parse.urlencode(params) @@ -51,6 +136,7 @@ def request(self, method, path, params=None): timeout=self.timeout, max_retries=self.max_retries, ) + entry["status"] = response.status data = response.body.decode("utf-8") if response.status in (200, 201, 202, 204): @@ -79,6 +165,7 @@ def request_raw(self, method, path, params=None): url = path if not url.startswith("/"): url = "/" + url + entry = self._record_request_start(method, _loggable_path(url)) if params: query = urllib.parse.urlencode(params) @@ -90,7 +177,7 @@ def request_raw(self, method, path, params=None): req_headers = {**self.headers} from . import http_retry - return http_retry.request_with_retries( + response = http_retry.request_with_retries( method, url, host="api.github.com", @@ -98,6 +185,8 @@ def request_raw(self, method, path, params=None): timeout=self.timeout, max_retries=self.max_retries, ) + entry["status"] = response.status + return response def get_all_pages(self, path, params=None, limit=None): all_items = [] diff --git a/src/github_usage/cli_email_report.py b/src/github_usage/cli_email_report.py index 1b3a43d..0b8ba2b 100644 --- a/src/github_usage/cli_email_report.py +++ b/src/github_usage/cli_email_report.py @@ -203,6 +203,7 @@ def _load_or_fetch_email_data( ) -> tuple[dict, str] | int: """Load cached email data or fetch fresh; return ``(data, username)`` or exit code.""" from .report_cache import ( + annotate_cache_hit, email_cache_params, format_cache_hit_message, load_cached_report, @@ -240,7 +241,7 @@ def _load_or_fetch_email_data( if cache_hit.from_cache and cached_data is not None: if cache_hit.age_seconds is not None and cache_hit.max_age_seconds is not None: print(format_cache_hit_message(cache_hit.age_seconds, cache_hit.max_age_seconds)) - return cached_data, cached_username or "unknown" + return annotate_cache_hit(cached_data), cached_username or "unknown" api_result = _init_github_api(token, args.timeout, args.max_retries) if isinstance(api_result, int): diff --git a/src/github_usage/email_report_html.py b/src/github_usage/email_report_html.py index e933509..825bd59 100644 --- a/src/github_usage/email_report_html.py +++ b/src/github_usage/email_report_html.py @@ -26,6 +26,7 @@ copilot_usage_summary_lines, ) from .repo_consumers import private_list_is_redundant +from .report_api_usage import api_usage_rows from .report_forecast_data import build_report_forecast, forecast_metric_rows from .report_helpers import fmt_price from .visibility import ( @@ -447,11 +448,14 @@ def _html_warning_block(warnings: list) -> list[str]: return parts -def _html_api_notes_block(estimate: dict) -> list[str]: +def _html_api_usage_block(estimate: dict) -> list[str]: + usage = api_usage_rows(estimate) notes = estimate.get("notes") or [] - if not notes: + if not usage and not notes: return [] - parts = ["

REST API Quota Notes

", "